Rails HATM (Has and belongs to many)
Nested forms with HABTM and HasManyThrough
Start with the models
has_many :events # creates ……
accepts_nested_attributes_for :events, :allow_destroy => true # creates….
attr_accessible :events_attributes # creates…
Then the Views
<%= simple_nested_form_for @person, :html => { :class => "form-horizontal" } do |f| %> <% if !@person.new_record? %>
f.simple_fields_for creates a "form in a form" (event_form in this case) <h3>Events in <%= @person.fullname %>'s life </h3>
<%= f.simple_fields_for :events do |event_form| %> <%= event_form.input :name, :label_html => {:class => 'horiz_input'}, :input_html => {:class => 'horiz_input'}, :placeholder => 'Event name', :readonly => readonly %> <%= event_form.input :date, :label_html => {:class => 'horiz_input'}, :input_html => {:class => 'horiz_input'}, :placeholder => 'Event date', :readonly => readonly %> <%= event_form.input :comment, :label_html => {:class => 'horiz_input'}, :input_html => {:class => 'horiz_input'}, :placeholder => 'Event comment', :readonly => readonly %> <% end %> If you DONT use event_form and use accepts_nested_attributes_for you might end up with the _destroy attribute attached to Person instead of the "event_attributes"
nested_form adds this JS helper <% if !readonly %> <p><%= f.link_to_add "Add an event", :events %></p> <% end %>
THROUGH
Model Person:
has_many :clicks has_many :users, :through => :clicks accepts_nested_attributes_for :users, :allow_destroy => true attr_accessible :users_attributes
Person.clicks.first.user_id
Person.clicks.first.count # How many times has this Person been clicked by this user….?