【问题标题】:Rails polymorphic comments associateRails 多态注释关联
【发布时间】:2018-07-09 02:25:23
【问题描述】:

尝试找出评论可以属于的多态关联,例如照片和用户。对用户的评论被视为“直接消息”。但我让用户关联有点混乱。

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class Photo < ActiveRecord::Base
  has_many :comments, as: :commentable, dependent: :destroy
end

class User < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  has_many :messages, as: :commentable
end

这是不正确的。理想情况下,user.comments 应检索 user_id == user.id 的所有评论记录,user.messages 应检索类型为 User 且它们是主题的所有评论。

【问题讨论】:

  • 在您的用户模型中...您有has_many :messages...您有消息模型吗?...换句话说,说这是不正确的可能无法提供足够的信息来回答问题。
  • @MarkMerritt 不,我没有消息模型。我想我的意图是创建一个指向评论的“消息”的关系名称。这有意义吗?
  • 知道了...我添加了一个答案...尝试研究我提供的链接!

标签: ruby-on-rails activerecord associations


【解决方案1】:

关系:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
  belongs_to :user
end

class Photo < ActiveRecord::Base
  has_many :comments, as: :commentable, dependent: :destroy
end

class User < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  has_many :messages, as: :commentable, class_name: 'Comment'
end

架构:

# Comments
 ...
 t.integer :user_id
 t.integer :commentable_id
 t.string :commentable_type
 ...

然后你可以调用:

@user.comments # Get all comments created by particular user
@user.messages # Get all comments where particular user is a subject

【讨论】:

  • 是的,这看起来和我的想法完全一样,我会尽快尝试。谢谢。
  • 非常感谢!只是我错过了class_name: 'Comment'。现在似乎一切正常。
【解决方案2】:

您是否已将外键和类型列添加到comments 表中?在迁移文件中:

  def change
    add_column :comments, :commentable_type, :integer
    add_column, :commentable_type, :string
    add_index :comments, [:commentable_type, :commentable_id]
  end

还要确保您有一个 Message 模型并且它具有关联

class Message < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  belongs_to :commentable, polymorphic: true
end

【讨论】:

  • 是的,我有。问题是当我打电话给user.messages 我得到NameError: uninitialized constant User::Message
  • 你的Message 模型是什么样的?
  • 是的,我认为这就是令人困惑的地方,我没有,而且我的做法是错误的。我的意图是创建与评论的关系,称为“消息”。
  • 是的,你需要创建一个Message模型然后,我会更新我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 2019-03-14
相关资源
最近更新 更多