首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用多对多关系

如何使用多对多关系
EN

Stack Overflow用户
提问于 2013-11-08 17:55:09
回答 2查看 49关注 0票数 1

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

代码语言:javascript
复制
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个关联类别的业务?

代码语言:javascript
复制
cat1 = Category.create(name: 'cat1')
cat2 = Category.create(name: 'cat2')
biz = Business.create(name: 'biz1'....
EN

回答 2

Stack Overflow用户

发布于 2013-11-08 18:14:17

一种选择是使用accepts_nested_attributes_for,如下所示:

代码语言:javascript
复制
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

然后你就可以像这样创建你的表单:

代码语言:javascript
复制
<%= 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对象:

代码语言:javascript
复制
#app/controllers/businesses_controller.rb
def new
    @business = Business.new
    2.times do { @business.categories.build }
end

或者,您必须从一个单独的函数调用,将类别数据输入到他们自己的表中,并将business_id设置为您想要的值

票数 1
EN

Stack Overflow用户

发布于 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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19856092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档