2012-04-23 106 views
3

我創建了一個消息模型,用戶可以將私人消息發送給其他用戶。但我不知道如何去通知用戶他/她有一個新的消息。有沒有人有辦法去做到這一點?或者如果有一個簡單的解決方案?如何發送用戶收到私人消息的通知

def create 
     @message = current_user.messages.build 
     @message.to_id = params[:message][:to_id] 
     @message.user_id = current_user.id 
     @message.content = params[:message][:content] 
     if @message.save 
      flash[:success ] = "Private Message Sent" 
     end 
     redirect_to user_path(params[:message][:to_id]) 
    end 

我可以告訴大家,悄悄話發送的發件人,但林不知道我怎麼可以通知創建一封新郵件的接收器。

幫助將不勝感激。謝謝=)

回答

4

首先,你可以提高你的控制器是這樣的:

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

+1

哦謝謝你的幫助!我希望我早點得到這個哈哈。我爲我的消息模型創建了一個read_at屬性,然後當用戶進入消息顯示操作時,它會創建一個時間戳。然後在我的應用程序助手中,我有一個方法來查看有多少個零對象(意味着未讀)。但我會仔細思考一下你的代碼。它有趣的=)以前從來沒有聽說過多態 – Sasha 2012-04-24 01:31:48

1

有任何數量的方式來通知收件人。你可以有一個發送電子郵件通知的工作進程,或者在你的站點上包含一個「收件箱」,顯示有多少人正在等待。

您還可以向收件人顯示「閃存」消息。你可以通過例如在基礎模板上包含一些代碼來檢查是否有尚未傳遞通知的未讀消息;如果沒有,則不會發生任何事情,如果有,則會顯示通知,並且顯示通知的事實將被記錄,以便它不會再次顯示。

+0

謝謝我做了一個未讀的計數就像一個收件箱=) – Sasha 2012-04-24 01:32:09

相關問題