【问题标题】:Rails single table inheritance with reference different columns in different modelsRails 单表继承,在不同模型中引用不同列
【发布时间】:2019-12-04 18:38:24
【问题描述】:

如何在使用单表继承从公共类继承的 2 个模型中拥有 2 个不同的引用列?

我找到了这个Single Table Inheritance (STI) column associations 的答案,但是就像 10 年前一样,现在在 Rails 中有更好的解决方案吗?

问题示例: 我想要类似的东西 考虑类(动物具有识别狮子/人类的类型)

class Animal < ApplicationRecord
    belongs_to :classA
end

class Lion < Animal
    belongs_to :two_legged
end

class Human < Animal
    belongs_to :four_legged
end

所以最后我希望Lion 属于classAtwo_legged;属于classAfour_legged的人类

除了在 Animal 中定义所有三个 belongs_to 并在 Lion & Human 中将不相关的列设为 nil 之外,还有其他更好的解决方案吗??

【问题讨论】:

  • 都是模型对吗?(动物、狮子、人类)
  • 这听起来有点像你想要polymorphic association@Rahul。
  • 都是模型 - 动物、狮子、人类、two_legged、four_legged

标签: ruby-on-rails ruby-on-rails-5 single-table-inheritance


【解决方案1】:

关注官方doc

class Animal < ApplicationRecord
    belongs_to :classA
    has_many :lions
    has_many :humans
end

class Lion < ApplicationRecord
    belongs_to :animal
end

class Human < ApplicationRecord
    belongs_to :animal
end

【讨论】:

  • 我不确定这如何回答这个问题。
  • two_leg 和four_leg 可能不是表格。可能是某种动物
  • 这个方案不使用单表继承,two_legged 和four legged 也是模型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多