Rails正确的方式来做多个关系

时间:2014-01-30 00:51:08

标签: ruby-on-rails rails-activerecord

User模型有很多notifications,还有很多sent_notifications

Notification模型有recipient_idcreator_id

我试图像这样建模这些关系:

User.rb

has_many :notifications, foreign_key: "recipient_id"
has_many :sent_notifications, foreign_key: "creator_id", class_name: "Notification"

notification.rb里

belongs_to :user

我的迁移如下所示:

class CreateNotifications < ActiveRecord::Migration
  def change
    create_table :notifications do |t|
      t.integer :recipient_id
      t.integer :creator_id
      t.integer :video_id
      t.string :message

      t.timestamps
    end
  end
end

但是,当我尝试访问Notification对象上的creator属性时,我得到:

undefined method `creator' for #<Notification:0x007ff4ddf514d0>

我做错了什么?

1 个答案:

答案 0 :(得分:4)

Notification.rb 应该是这样的:

belongs_to :creator,   class_name: 'User'
belongs_to :recipient, class_name: 'User'