Saturday 8 April 2017

Notification in rails

Notification to all users

1. rails g model notification user_id:integer receiver_id:integer notificable_id:integer notificable_type:string body:string is_read:boolean

2. Notification model

belongs_to :user
belongs_to :receiver, class_name: "User"
belongs_to :notificable, polymorphic: true

3. User model
  has_many :notifications
  has_many :receive_notifications, class_name: "User", foreign_key: "receiver_id"

4. in home controller on view you wanna show

 def index
  @receive_notifications = current_user.receive_notifications
  @notifications = current_user.notifications
 end

5. go to header in notification windows

<% if @receive_notifications %>
Receive
<% @receive_notifications.each do |ra| %>
<%= ra.body %>
<% end %>
<% end %>
<br>
<% if @notifications %>
Send
<% @notifications.each do |ra| %>
<%= ra.body %>
<% end %>
<% end %>
6. in post controller create action.
Because post will show to all user which user has created post on that.

        User.all.each do |u|
          @post.notifications.create(user_id: current_user.id, receiver_id: u.id, body: "#{current_user.email} Posted #{@post.title}" , notificable: @post) unless u == current_user
        end

 7. route.rb
  resources :notifications

  Please note: you can make more method like

  def mark_read
  end

No comments:

Post a Comment

Revert last commit or second last and more....

 Git revert commit_id -m 1 this command willl revert last commit  Git revert commit_id -m 2 this command will revert second commit with same...