我在业务和类别之间有多对多的关系
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'....发布于 2013-11-08 18:14:17
一种选择是使用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 %>为此,您必须在控制器中构建category对象:
#app/controllers/businesses_controller.rb
def new
@business = Business.new
2.times do { @business.categories.build }
end或者,您必须从一个单独的函数调用,将类别数据输入到他们自己的表中,并将business_id设置为您想要的值
发布于 2013-11-08 18:20:48
这是指定多对多关系的另一种方式
类Business < ActiveRecord::Base
-- has_many :business_categories
* has_many :类别,通过::business_categories
结束
类类别< ActiveRecord::Base
-- has_many :business_categories
* has_many :企业,通过::business_categories
结束
类Business_category < ActiveRecord::Base
** belongs_to :类别
** belongs_to :企业
结束
请参阅以下链接::http://guides.rubyonrails.org/association_basics.html
https://stackoverflow.com/questions/19856092
复制相似问题