【问题标题】:Polymorphic assosiation多态关联
【发布时间】:2021-02-10 13:21:06
【问题描述】:

我有模型评论和主题。我想创建另一个名为 Storage 的模型。 所以现在我在Storage.rb 中有这个:

  with_options inverse_of: :storage do
    has_many :comments, as: :editable
    has_many :topics, as: :editable
  end

迁移:

  t.references :editable, polymorphic: true
  t.timestamps

存储表:

    t.string "editable_type", null: false
    t.bigint "editable_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["editable_type", "editable_id"], name: "index_storages_on_editable_type_and_editable_id"

Comment.rb:

belongs_to :editable, polymorphic: true, optional: true

Topic.rb:

belongs_to :editable, polymorphic: true, optional: true

我尝试使用多态关联的全部原因是我可以从 Storage 中获取 Comment 对象。就像评论以某种方式进入存储一样,我应该能够像Storage.particular_comment.user_id 那样做一些事情,并获取写此评论的用户的 ID。

但是,我无法这样做。我想在我的联想中某处有错误,但我只是没有看到/理解它。谢谢!

【问题讨论】:

  • 你是如何查询评论的? Storage.where(editable: Comment.find_by(user_id: 1)) 应该会在存储表中为您提供评论。从那里,在不了解更多关联的情况下,您可以获得用户 ID
  • 解释此存储模型的总体目标可能会有所帮助。根据您所写的内容,这似乎是多余的,并且可以使用您现在拥有的两个模型来实现。
  • @sam Storage 模型的目标是简单地拥有一个 CommentTopic 的实例,以便您可以随时访问它。
  • @Int'lManOfCodingMystery 这是一个相当长的查询,目标是让所有内容都简短而有效。我能够在下面的回答中实现这一点
  • @Giasod,对不起,我以为你想查询,但还没有正确的 Storage 实例

标签: ruby-on-rails ruby polymorphic-associations


【解决方案1】:

我设法解决了这个问题。事实证明,我的主要错误是我没有正确理解这些关联。以最少的查询和努力做到这一点的正确方法如下:

Storage.rb:

  belongs_to :editable, optional: true, inverse_of: :storages, polymorphic: true
  belongs_to :topic, inverse_of: :storages, optional: true
  belongs_to :comment, inverse_of: :storages, optional: true

Comment.rbTopic.rb

has_many :storages, as: :editable, inverse_of: :comment, dependent: :nullify

has_many :storages, as: :editable, inverse_of: :topic, dependent: :nullify

存储表保持不变。

上述关联可以达到以下结果:

> c = Comment.last
> st = Storage.create!(:editable => c)
> st
=> #<Storage:0x007fb45d8fcb40> {
             id: 1,
  editable_type: "Comment",
    editable_id: 9,
     created_at: Thu, 11 Feb 2021 05:45:10 EST -05:00,
     updated_at: Thu, 11 Feb 2021 05:45:10 EST -05:00

现在很容易获得所需的任何信息,而无需冗长而复杂的查询:


> st.editable
=> #<Comment:0x0055ddca8eddb8> {
          id: 9,
     user_id: 392,
    topic_id: 1183,
     content: "test",
  created_at: Wed, 10 Feb 2021 11:17:42 EST -05:00,
  updated_at: Wed, 10 Feb 2021 11:17:42 EST -05:00
> st.editable.user_id
=> 392
> st.editable.content
=> "test"

我希望这会对某人有所帮助!感谢 cmets!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 2013-02-28
    • 2011-04-08
    • 1970-01-01
    相关资源
    最近更新 更多