我正在学习Rails及其Active Records,我想设置通知并将它们发送给用户并注册谁发送它,我有这样的东西:通知模型(我不知道设置'是否正确:发件人'和':收件人'就像我一样):
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'
通过在模型迁移中添加索引并使我的模型保持如下来实现:
移民:
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