【问题标题】:Rails model has_many association to the same modelRails 模型 has_many 关联到同一个模型
【发布时间】:2019-03-23 11:47:04
【问题描述】:

我有两个模型:CategorySubcategory

我可能会遇到 Subcategory 将包含更多 Subcategories

的情况

如何使用 rails 关联来做到这一点?

现在我的代码:

category.rb

class Category < ApplicationRecord
  has_many :subcategories, :dependent => :destroy
end

subcategory.rb

class Subcategory < ApplicationRecord
  belongs_to :category
  has_many :products, :dependent => :destroy
end

可能的例子:

Category 可读 --> Subcategory 书籍 --> Subcategory 儿童书籍 --> 产品 p>

【问题讨论】:

  • 儿童读物只能在一个子类别下,还是可以在一个类别下?像Category Readable --> Subcategory Books for kids 这种情况可能吗?

标签: ruby-on-rails postgresql migration associations activemodel


【解决方案1】:

这是多态 belongs_to 关联的一个很好的例子。

#on Subcategory model
belongs_to :parent, polymorphic: true
has_many :subcategories, as: :parent, dependent: :destroy

#on Category model
has_many :subcategories, as: :parent, dependent: :destroy


#on the database
t.references :parent, polymorphic: true, index: true # this adds two columns, parent_id and parent_type

现在您可以将任何东西指定为子类别的父级,您可以调用 subcategory.parent 来获取类别或子类别

https://guides.rubyonrails.org/association_basics.html#polymorphic-associations

【讨论】:

  • 成功了! 1) rails 生成迁移 AddParentRefToSubcategories parent:references 2) 打开并编辑迁移到add_reference :subcategories, :parent, polymorphic: true, index: true 3) rake db:migrate 4)profit
【解决方案2】:

您可以尝试通过迁移将 subcategory_id 添加到您的子类别模型中,并在您的子类别模型中添加has_many :subcategories。 或者您可以添加 belongs_to :parent, :class_name => "Subcategory", :foreign_key => "parent_subcategory_id" has_many :child_subcategories, :class_name => "Subcategory", :foreign_key => "child_subcategory_id"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    相关资源
    最近更新 更多