【发布时间】: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模型的目标是简单地拥有一个Comment或Topic的实例,以便您可以随时访问它。 -
@Int'lManOfCodingMystery 这是一个相当长的查询,目标是让所有内容都简短而有效。我能够在下面的回答中实现这一点
-
@Giasod,对不起,我以为你想查询,但还没有正确的 Storage 实例
标签: ruby-on-rails ruby polymorphic-associations