【问题标题】:Notification associations - what's the right way to do it?通知关联 - 正确的做法是什么?
【发布时间】:2013-02-01 18:00:12
【问题描述】:

我有一个带有用户模型的 Rails 3.2 应用程序。我想添加一个可以由以下用例触发的通知机制:

  • 喜欢某人的个人资料
  • 评论某人的个人资料
  • 关注某人

在所有情况下,一位用户都会根据他的行为生成通知,另一位用户将收到该通知。因此,存在通知的发送者和接收者。

我现在正在思考如何构建我的关联。到目前为止,我的模型如下所示:

Notification.rb

attr_accessible :content, :read_at, :recipient_id, :sender_id

belongs_to :sender,     class: :user
belongs_to :recipient,  class: :user

用户.rb

has_many :notifications, as: :recipient, dependent: :destroy, foreign_key: :recipient_id
has_many :notifications, as: :sender, dependent: :destroy, foreign_key: :sender_id

这个伪代码只能帮助理解我需要什么——让我很困惑的是,我在通知模型中两次引用了用户模型,并且用户以两种不同的方式拥有许多通知。

所以,我的问题是:

  • 您将如何调整上述关联?
  • 你会怎么称呼他们?
  • 如何在无需编写作用域的情况下调用用户模型上的所有已发送通知和所有已接收通知?
  • 这是正确的方法,还是我应该在两个地方使用连接表以避免两次引用用户?

谢谢!

解决方案

将 Shane 的解决方案用文字表达出来,这就是模型的外观。这真的比我想象的要容易得多。我以为我必须在这里做一些魔术 - 但 Rails 又一次以其惊人的简单性欺骗了我!嗯,这就是我如此喜欢它的原因。

非常感谢,谢恩!

Notification.rb

attr_accessible :content, :read_at, :recipient, :recipient_id, :sender, :sender_id

belongs_to :sender, class_name: "User"
belongs_to :recipient, class_name: "User"

用户.rb

has_many :received_notifications, class_name: "Notification", foreign_key: "recipient_id", dependent: :destroy
has_many :sent_notifications, class_name: "Notification", foreign_key: "sender_id", dependent: :destroy

【问题讨论】:

  • 你上面表达的关系是这类关系的规范。在利用同一个类的模型中拥有多个映射并没有什么坏处。

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


【解决方案1】:

这是完全正常的。以下是在流行的开源应用 Redmine 中使用的相同模式的示例:

https://github.com/edavis10/redmine/blob/master/app/models/workflow_rule.rb#L23-L24

至于需要一种可以同时接收发送和接收通知的方法,这里的答案很适合基本需求。

Rails Model has_many with multiple foreign_keys

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多