Ruby on rails RoR多对多关联
我通过CategoriesSpecifications表建立了类别和规格模型以及多对多关联,如下所示:Ruby on rails RoR多对多关联,ruby-on-rails,ruby,many-to-many,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 通过类别选择
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
类别
推荐阅读:假设您有以下内容:
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.find(1).specifications