首先,你可以提高你的控制力,如:
def create
@message = current_user.messages.new(params[:message])
if @message.save
flash[:message] = "Private Message Sent"
end
redirect_to user_path(@message.to_id)
end
之后,在你的模式中:
# app/models/message.rb
class Message < ActiveRecord::Base
belongs_to :user
belongs_to :recipient, class_name: User , foreign_key: :to_id
has_many :notifications, as: :event
after_create :send_notification
private
def send_notification(message)
message.notifications.create(user: message.recipient)
end
end
# app/models/user.rb
class User < ActiveRecord::Base
has_many :messages
has_many :messages_received, class_name: Message , foreign_key: :to_id
has_many :notifications
end
# app/models/notification.rb
class Notification < ActiveRecord::Base
belongs_to :user
belongs_to :event, polymorphic: true
end
<代码>Notification模型允许你储存不同“events”的用户通知。 您甚至可以储存通知是否读到,或者在_create <>/code>后建立,以便向通知用户发送电子邮件。
The migration for this Notification
model will be:
# db/migrate/create_notifications.rb
class CreateNotifications < ActiveRecord::Migration
def self.up
create_table :notifications do |t|
t.integer :user_id
t.string :event_type
t.string :event_id
t.boolean :read, default: false
t.timestamps
end
end
def self.down
drop_table :notifications
end
end
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html” rel=“nofollow”>。