我在业务和类别之间存在多对多的关系
class Business < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :businesses
end
如何创建包含2个相关类别的商家?
cat1 = Category.create(name: 'cat1')
cat2 = Category.create(name: 'cat2')
biz = Business.create(name: 'biz1'....
答案 0 :(得分:1)
一种选择是使用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
设置为您想要的
答案 1 :(得分:-1)
类业务&lt;的ActiveRecord :: Base的
has_many:business_categories
has_many:类别,通过:: business_categories
端
类别&lt;的ActiveRecord :: Base的
has_many:business_categories
has_many:企业,通过:: business_categories
端
class Business_category&lt;的ActiveRecord :: Base的
belongs_to:类别
belongs_to:商家
端
请参阅以下链接:: http://guides.rubyonrails.org/association_basics.html