1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
=begin
This is an extension to Ryan Bates excellent screencast http://railscasts.com/episodes/197-nested-model-form-part-2
I show here a way to adapt his technique for many to many associations (has_many through)
In this exemple i have products with a many to many relationship to categories

the helper methods and javascript functions shown in the screencast remain unchanged
=end

# in Product model
has_many :categorizations
has_many :categories, :through => :categorizations

accepts_nested_attributes_for :categorizations, :reject_if => lambda { |c| c['category_name'].blank? }, :allow_destroy => true

# in categorization model
belongs_to :product
belongs_to :category

def category_name
  category.name if category
end

def category_name=(name)
  self.category = Category.find_or_create_by_name(name);
end

# _categorization_fields.html.erb (autocomplete is done with the "repeated_auto_complete" gem, http://github.com/patshaughnessy/auto_complete)
<div class="fields">
  <%= f.text_field_with_auto_complete :category_name,{},{:url => formatted_categories_path(:js), :param_name => 'search', :method => :get} %>
  <%= link_to_remove_fields "remove", f %>
</div>

# in the form
<% f.fields_for :categorizations do |c_form| %>
    <%= render 'categorization_fields', :f => c_form %>
<% end %>
<p><%= link_to_add_fields "Add Category", f, :categorizations %></p>