开发者

Rails 3 has_and_belongs_to_many and accepts_nested_attributes_for implementation

I need help with implementing the nested form for a has_and_belongs_to_many

I have the following:

Models

class Country < ActiveRecord::Base
  has_and_belongs_to_many :categories
  accepts_nested_attributes_for :categories, :allow_destroy => true
end

class Category < ActiveRecord::Base
  has_and_belongs_to_many :countries
end

Migrations

class CreateCountries < ActiveRecord::Migration
  def self.up
    create_table :countries do |t|
      t.string :name
      t.string :code
      t.boolean :active
      t.timestamps
    end
  end

  def self.down
    drop_table :countries
  end
end

class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.sting :name
      t.string :description
      t.boolean :active
      t.timestamps
    end
  end

  def self.down
    drop_table :categories
  end
end

class CreateCategoriesCountries < ActiveRecord::Migration
  def s开发者_如何学编程elf.up
    create_table :categories_countries, :id => false do |t|
        t.references :category
        t.references :country
    end
    add_index(:categories_countries, [:category_id, :country_id], :unique => true)
  end

  def self.down
    drop_table :categories_countries
  end
end

View for Country where I want the nested categories in the form of checkboxes

<%= form_for @country do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :code %><br />
    <%= f.text_field :code %>
  </p>
  <p>
    <%= f.label :active %><br />
    <%= f.check_box :active %>
  </p>
  <p><%= f.submit %></p>
<% end %>


<%= form_for @country do |f| %>
  <%= f.error_messages %>
  ...
  <% Categories.all.each do |category| %>
  <p>
    <%= f.label category.name %>
    // don't use f here
    <%= check_box :categories_ids,
                  category.id,
                  @country.categories.include?(category),
                  :name=>'country[categories_ids][]' %>
  </p>
  <% end %>
  <p><%= f.submit %></p>
<% end %> 

source: Handle check box forms with an `:has_many :through` Record Association => http://millarian.com/programming/ruby-on-rails/quick-tip-has_many-through-checkboxes/

Why do you use :allow_destroy => true ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜