如何使用多对多的关系

时间:2013-11-08 09:55:09

标签: ruby-on-rails ruby

我在业务和类别之间存在多对多的关系

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

2 个答案:

答案 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