我有类别和规范模型,以及通过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通过类别选择所有规格的最佳实践和最快捷方式是什么
发布于 2015-01-07 01:33:44
@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
发布于 2015-01-07 01:34:24
假设您有如下内容:
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
Category.find(1).specificationshttps://stackoverflow.com/questions/27803894
复制相似问题