作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个模型:Category
和 Subcategory
而且我可以遇到 Subcategory 将包含更多 Subcategories
的情况如何使用 Rails 关联来实现?
现在我的代码:
类别.rb
class Category < ApplicationRecord
has_many :subcategories, :dependent => :destroy
end
subcategory.rb
class Subcategory < ApplicationRecord
belongs_to :category
has_many :products, :dependent => :destroy
end
可能的例子:
类别
可读 --> 子类别
书籍 --> 子类别
< strong> child 读物 --> 产品
最佳答案
这是多态 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
关于ruby-on-rails - Rails 模型与同一模型有_many 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55313410/
我是一名优秀的程序员,十分优秀!