2013-02-01 29 views
1

我有一个用户模型的Rails 3.2应用程序。我想补充一点,可以通过下面的用例被触发的通知机制:通知组织 - 什么是正确的方法?

  • 点击喜欢某人的个人资料
  • 谈到某人的个人资料
  • 继有人

在所有情况下,一个用户根据他的行为生成另一个用户将收到的通知。所以,有一个发件人和收件人的通知。

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

notification.rb里

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

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

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" 

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 
+0

上面表达的关系是这些类型关系的规范。在利用同一类的模型中进行多重映射没有任何坏处。 –

回答

相关问题