Rails协会多个外键相同的表

时间:2018-08-07 00:25:28

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

我正在学习Rails及其活动记录,我想设置通知并将其发送给用户并注册发送它的用户,我有这样的事情: 通知模型(我不知道像我一样设置':sender'和':reciever'是否正确):

class Notification < ApplicationRecord
    belongs_to :sender, class_name: 'User', foreign_key: 'sender_id'
    belongs_to :reciever, class_name: 'User', foreign_key: 'reciever_id'
end

用户模型:

class User < ApplicationRecord
    has_many :notifications
end

我能做

user.notifcations.new(:message => "New notification", :sender => User.first)

但是当我保存(user.save)时,它显示:

  

ActiveModel :: MissingAttributeError:无法写入未知属性'sender_id'

1 个答案:

答案 0 :(得分:0)

在模型迁移中添加索引并保持我的模型如下:

迁移:

class CreateNotifications < ActiveRecord::Migration[5.1]
  def change
    create_table :notifications do |t|
      # Adding index
      t.integer :sender_id

      t.text :message
      t.boolean :seen

      t.boolean :deleted

      t.timestamps
    end
    add_index :notifications, :sender_id
  end
end

用户模型:

class User < ApplicationRecord
    has_many :notifications, foreign_key: 'user_id'
    has_many :notifications_sended, class_name: 'Notification', foreign_key: 'sender_id'
end

通知模型:

class Notification < ApplicationRecord
    belongs_to :reciever, class_name: 'User', foreign_key: 'user_id'
    belongs_to :sender, class_name: 'User', foreign_key: 'sender_id'
end

还进行了AddUserToNotification迁移:

rails g migration AddUserToNotification user:references

我可以这样做:

User.first.notifications.new(:message => "Hi", :sender => User.second)

并且:

User.first.notifications # Shows the notification
User.second.notifications_sended # Shows the same notification