【问题标题】:Rails model belongs to parent model through many models in the middleRails模型通过中间很多模型属于父模型
【发布时间】:2018-06-21 06:53:08
【问题描述】:

我有模型之间的显示关系。问题是,模型 Formulari 可以属于一个主题,或者属于一个区域,或者属于一个主题,或者属于 Subthema。这就是我使用可选选项的原因:true

class Formulari < ApplicationRecord
  belongs_to :topic, optional: true
  belongs_to :area, optional: true
  belongs_to :thema, optional: true
  belongs_to :subthema, optional: true

  ### how to make this work?
  ### it just uses the last one
  has_one :user, through: :area
  has_one :user, through: :thema
end

我想访问@formulari.user,所以我需要通过关系使用has_one,但是由于我有路径选项,所以很棘手。如果我通过关系写了多个 has_one,rails 只取其中一个。

我不知道如何通过与模型的关系来告诉 rails,多个 has_one。

任何帮助将不胜感激。 谢谢

【问题讨论】:

标签: ruby-on-rails activerecord


【解决方案1】:

只需像下面这样使用 ActiveRecord 的多态关联

class Formulari < ApplicationRecord
  belongs_to :formularable, polymorphic: true

  has_one :user
end

那么其他模型会有

class Areas
   has_many :formulari, as: :formularable
end

还有其他两个模型。是的 - 为什么不直接将user_idtopic_id 添加到Formulari。这只需要更多的逻辑来在更新时分配和重新分配它们。在我看来,这比从subthema 一直请求用户(使用长连接或长链请求导致数据库响应缓慢)更令人沮丧。

如果您最终使用多态然后正确添加列read this doc 如果您遇到任何问题,请随时提出问题,但我鼓励您阅读文档或观看 railscasts。

【讨论】:

  • 非常感谢,是的,它应该可以工作。一位朋友告诉我这种方法,但我想看看我是否可以在没有任何高级的东西(如多态)的情况下解决问题。
猜你喜欢
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多