【问题标题】:Rails 3 has_and_belongs_to_many and accepts_nested_attributes_for implementationRails 3 has_and_belongs_to_many 和 accept_nested_attributes_for 实现
【发布时间】:2011-09-30 14:30:18
【问题描述】:

我需要帮助来实现 has_and_belongs_to_many 的嵌套表单

我有以下几点:

型号

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

迁移

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 self.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

以复选框的形式查看我想要嵌套类别的国家/地区

<%= 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 %>

【问题讨论】:

  • 好吧,我不确定如何实现嵌套类别。正在寻求帮助。

标签: ruby-on-rails-3 has-and-belongs-to-many


【解决方案1】:
<%= 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 %> 

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

你为什么使用 :allow_destroy => true ?

【讨论】:

  • 是的,你只是想设置关联,例如不需要 field_for()。
  • 由于某种原因,代码最终给出了许多错误。最后我决定不使用“accepts_nested_attributes_for”部分,而只采用显示复选框的简单方法。
猜你喜欢
  • 2012-01-14
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多