How to send a notification to a user who has received a private message

I created a messaging model in which a user can send a private message to another user. however, I am not sure how to report that the user has received a new message. Does anyone have a way to do this? or if there was a simple solution?

    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

I can tell the sender that a private message was sent, but I'm not sure how I can notify the recipient of the creation of a new private message.

help would be appreciated. thanks =)

+3
source share
2 answers

Firstly, you can improve your controller as follows:

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

Then in your models:

# 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 .

+4

. , "" , , - .

"flash" . , , - , , - , ; , , , , , , , .

+1

All Articles