首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RoR多对多关联

RoR多对多关联
EN

Stack Overflow用户
提问于 2015-01-07 01:25:13
回答 2查看 54关注 0票数 0

我有类别和规范模型,以及通过CategoriesSpecifications表的多对多关联,该表如下所示:

代码语言:javascript
复制
create_table :categories_specifications, id: false do |t|
   t.belongs_to :specification, null: false
   t.belongs_to :category, null: false
   t.integer :status, null: false, default: 0
end

通过类别选择所有规格的最佳实践和最快捷方式是什么

EN

回答 2

Stack Overflow用户

发布于 2015-01-07 01:33:44

代码语言:javascript
复制
@category = Category.first
@category.specifications # this is the shortest way to select all specifications via Category

当然,要确保在您的模型中声明了关联:

代码语言:javascript
复制
class Category < ActiveRecord::Base
  has_many :categories_specifications
  has_many :specifications, through: :categories_specifications
end

class Specification < ActiveRecord::Base
  has_many :categories_specifications
  has_many :categories, through: :categories_specifications
end

class CategoriesSpecification < ActiveRecord::Base
  belongs_to :category
  belongs_to :specification
end

推荐阅读: http://guides.rubyonrails.org/association_basics.html

票数 0
EN

Stack Overflow用户

发布于 2015-01-07 01:34:24

假设您有如下内容:

代码语言:javascript
复制
class Category < ActiveRecord::Base
  has_many :specifications
  has_many :categories, :through => :categories_specifications
end

class CategoriesSpecification < ActiveRecord::Base
  belongs_to :category
  belongs_to :specification
end

class Specification < ActiveRecord::Base
  has_many :categories_specifications
  has_many :categories, :through => :categories_specifications
end

您可以简单地找到category,然后选择all specifications

代码语言:javascript
复制
Category.find(1).specifications
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27803894

复制
相关文章

相似问题

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