HABTM Example

Complex forms on a HABTM association.

Using code borrowed from Pat (patshaughnessy.net), whose view_mapper finally taught this hobbyist hacker to write forms.

Hopefully this will fit snugly into someone else’s gem

Installation

  • Install as a gem:

    # Add to your Gemfile
    gem "anaf_habtm"
    
  • or as a plugin

    rails plugin install git://github.com/tylergannon/anaf_habtm.git
    

Run the generator to place the javascript in the right place:

rails generate anaf_habtm

Add the following to your layout:

<%= javascript_include_tag 'nested_attributes.js' %>

Usage

Inside your model, call anaf_habtm just as you would call has_and_belongs_to_many, except now you need to offer a code block telling rails what to do with each object. The plugin will handle deleting stuff.

# Basically, your code block needs to return an object of the correct
# type for your association collection, or else nil if your code
# determines that the object should be rejected.
class Customer < ActiveRecord::Base
  anaf_habtm :orders, :autosave => true, :uniq => false do |params, order|
    order = order ||= Order.new
    order.attributes = params
    logger.error params.inspect
    order
  end
end

class Order < ActiveRecord::Base
  has_and_belongs_to_many :customers
  anaf_habtm :items, :autosave => true, :uniq => false do |params, item|
    logger.error "ITEM:::  #{params.inspect}"
    item ||= Item.find_or_create_by_name(params["name"])
  end
end

Additional info

See the example app at github.com/tylergannon/accepts-nested-attributes-habtm-example for more details.

Also check out Pat’s view_mapper… it can generate the code you need inside your views.

github.com/patshaughnessy/view_mapper