首先,你可以提高你的控制器是這樣的:
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
模式允許你存儲用戶的通知不同的「事件」。您甚至可以存儲是否已閱讀通知,或者設置after_create
回撥以向通知的用戶發送電子郵件。
此Notification
模型的遷移將是:
# 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
您可以閱讀有關Rails的關聯選項here。
哦謝謝你的幫助!我希望我早點得到這個哈哈。我爲我的消息模型創建了一個read_at屬性,然後當用戶進入消息顯示操作時,它會創建一個時間戳。然後在我的應用程序助手中,我有一個方法來查看有多少個零對象(意味着未讀)。但我會仔細思考一下你的代碼。它有趣的=)以前從來沒有聽說過多態 – Sasha 2012-04-24 01:31:48