【问题标题】:Rails Association multiple foreign key same tableRails 关联多个外键同一张表
【发布时间】:2018-08-07 00:25:28
【问题描述】:

我正在学习 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: can't write unknown attribute 'sender_id'

【问题讨论】:

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


    【解决方案1】:

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

    迁移:

    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
    

    【讨论】:

      猜你喜欢
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      相关资源
      最近更新 更多