一种选择是使用accepts_nested_attributes_for
,如下所示:
class Business < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :categories
accepts_nested_attributes_for :businesses_categories
end
class Category < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :businesses
end
class BusinessesCategories < ActiveRecord::Base
accepts_nested_attributes_for :categories
end
然后,您就可以像这样创建表单:
<%= form_for @business do |f| %>
<%= f.fields_for :businesses_categories do |b| %>
<%= b.fields_for :categories do |c| %>
<%= c.text_field :cat %>
<% end %>
<% end %>
<% end %>
为此,您必须在控制器中构建类别对象:
#app/controllers/businesses_controller.rb
def new
@business = Business.new
2.times do { @business.categories.build }
end
或者您必须从一个单独的函数调用将类别数据输入到他们自己的表中,并将其business_id
设置为您想要的表