Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RoR多对多关联_Ruby On Rails_Ruby_Many To Many - Fatal编程技术网

Ruby on rails RoR多对多关联

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 通过类别选择

我通过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
类别

推荐阅读:

假设您有以下内容:

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