繁体   English   中英

RoR多对多关联

[英]RoR Many to many association

我有类别和规格模型,并且通过CategoriesSpecifications表建立了许多对许多关联,如下所示:

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

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

@category = Category.first
@category.specifications # this is the shortest way to select all specifications via Category

当然,请确保在模型中声明了关联:

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

假设您具有以下内容:

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然后选择所有specifications

Category.find(1).specifications

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM