Rails 添加对相关模型的引用

Rails adding reference to related models

我有以下设置来处理类别和子类别。

Category.rb

class Category < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged

  has_many :subcategories
  has_many :products ,:through => :subcategories
end

Subcategory.rb

class Subcategory < ActiveRecord::Base
  belongs_to :category
  has_many :products
end

Product.rb

class Product < ActiveRecord::Base
  acts_as_taggable
  extend FriendlyId
  friendly_id :name, use: :slugged
  belongs_to :subcategory
end

我需要在产品模型中添加 category_id:integer & subcategory_id:integer 使其工作,还是 Rails 处理这是自动给我的吗?

我认为您不需要在产品模型中添加 category_id:integer & subcategory_id:integer

它们应该写在迁移文件中。像这样:

create_table :products do |t|
    t.references :category, :subcategory
    ...
end

或者,也许我没理解你的问题?

是的,您需要将 category_id 和 subcategory_id 添加到模型迁移文件中才能使其正常工作。 Rails 不会为你做,除非你明智地使用 rails generate 语法。 例如。首先你创建 Category 模型

rails generate model Category name:string

然后创建 Subcategory 模型传递类别作为参考。

rails generate model Subcategory name:string category:references

然后创建 Product 模型传递子类别作为参考

rails generate model Product name:string subcategory:references

这会自动将 category_idsubcategory_id 添加到迁移文件中。不过,您必须自己在模型中编写关系(即,只有 has_many 部分)

如果您没有误操作,您可以通过 rails generate 命令或手动创建新的迁移。

rails g migration AddCategoryRefToSubcategories category:references
rails g migration AddSubcategoryRefToProducts subcategory:references

这将为您创建适当的迁移文件,然后 运行 rake db:migrate。 :)