1

我在企业和类别之间有多对多的关系

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

2 回答 2

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设置为您想要的表

于 2013-11-08T10:14:16.810 回答
-1

这是指定多对多关系的另一种方式

业务类 < ActiveRecord::Base
   has_many :business_categories
   has_many :categories, through: :business_categories
end

class Category < ActiveRecord::Base
   has_many :business_categories
   has_many :businesses, through: :business_categories
end

类 Business_category < ActiveRecord::Base
   belongs_to :categories
   belongs_to :businesses
end

请参阅下面的链接:http: //guides.rubyonrails.org/association_basics.html

于 2013-11-08T10:20:48.033 回答