【问题标题】:Polymorphic and non-polymorphic associations on the same model同一模型上的多态和非多态关联
【发布时间】:2013-08-29 01:23:21
【问题描述】:

我有一个 Log 模型,它具有多态关联和另一个与 User 模型的关联:

class Log < ActiveRecord::Base
  belongs_to :loggable, polymorphic: true
  belongs_to :user
end

在我的 User 模型中,我与 Log 模型有一个 has_many 关联:

class User < ActiveRecord::Base
  has_many :logs
end

我想在 User 模型中有另一个关联,如下所示:

class User < ActiveRecord::Base
  has_many :logs
  has_many :logs, as: :loggable
end

但我想这两个关联会相互冲突(我不知道,没试过)......

那么这是解决这个问题的正确方法吗?还是有更好的方法?

【问题讨论】:

  • 为什么需要另一个关联来记录日志?
  • 我需要一个关联,其中用户是“演员”,而用户是“主题”。例如:“user1在contact2上添加了注释”(user1是actor)和user2暂停user1(user1是subject,user2是actor)
  • 您只记录用户或其他模型?您不能在 Logs 表(actor_id、subject_id)上执行此操作,在 User 模型上使用和创建范围吗?
  • 我正在记录多个模型。 @Marek Lipka 提供了正确的解决方案,其中 Log 模型尽可能保持通用。

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


【解决方案1】:

像这样重命名你的一个协会怎么样:

class User < ActiveRecord::Base
  has_many :user_logs, class_name: 'Log'
  has_many :logs, as: :loggable
end

要获取与给定用户关联的所有日志,您可以像这样在Log 模型上设置范围:

class Log < ActiveRecord::Base
  belongs_to :loggable, polymorphic: true
  belongs_to :user

  scope :for_user, lambda { |user|
    where('user_id = :user_id OR (loggable_type = "User" AND loggable_id = :user_id)', user_id: user.id)
  }
end

【讨论】:

  • 这是一个我没有想到的好主意,但如果可能的话,我想用一个命令(正确排序)获取与用户关联的所有日志。因此,如果有办法以相同的方式命名这两个关联,那将是理想的。否则,我很乐意接受您的回答。
  • @AzizLight 我编辑了我的答案。我认为这是处理您的问题的最佳方式。
猜你喜欢
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
相关资源
最近更新 更多