RoR很多很多协会

时间:2015-01-06 17:25:13

标签: ruby-on-rails ruby many-to-many

我有类别和规范模型以及通过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

通过类别

选择所有规格的最佳做法和最短路径是什么

2 个答案:

答案 0 :(得分:0)

@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

答案 1 :(得分:0)

假设您有以下内容:

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