【问题标题】:Can a single model "belong_to" more than one parent model?单个模型可以“belong_to”多个父模型吗?
【发布时间】:2009-10-09 00:59:00
【问题描述】:

就像在 StackOverflow 上一样,在我的应用中,用户可以写问题也可以提供答案:

class User < ActiveRecord::Base
  has_many :questions
  has_many :answers
end

class Question < ActiveRecord::Base
  has_many :answers
  belongs_to :user
end


class Answer < ActiveRecord::Base
  belongs_to :question
  belongs_to :user
end

我的问题与上面的答案模型有关:

用户和问题模型都可以使用Answerbelong_to 吗?

我有一种感觉,我在某处读到一个模型只能有一个外键。如果是这样,我该如何纠正?

【问题讨论】:

    标签: ruby-on-rails relationships


    【解决方案1】:

    是的,这完全没问题,随着您的域模型变得越来越复杂,您将拥有许多具有许多 belongs_to 的模型。我不知道您会从哪里读到模型只能有一个外键。

    【讨论】:

    • 很多人认为,一个类只能有1个parent,模型只能有1个belongs_to。一种误解,但实际上很常见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2012-02-15
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多