A simple notification feature in Rails. (Only when followed for the time being)
config/routes.rb
resources :notifications, only: [:index]
$ rails g controller notifications
$ rails g model Notification visitor_id:integer visited_id:integer
$ rails db:migrate
app/models/user.rb
has_many :active_notifications, class_name: "Notification", foreign_key: "visitor_id", dependent: :destroy
has_many :passive_notifications, class_name: "Notification", foreign_key: "visited_id", dependent: :destroy
def create_notification_follow!(current_user)
temp = Notification.where(["visitor_id = ? and visited_id = ? ",current_user.id, id])
if temp.blank?
notification = current_user.active_notifications.new(visited_id: id)
notification.save if notification.valid?
end
end
app/models/notification.rb
belongs_to :visitor, class_name: 'User', foreign_key: 'visitor_id'
belongs_to :visited, class_name: 'User', foreign_key: 'visited_id'
app/controllers/relationships_controller.rb
def create
@user = User.find(params[:user_id])
current_user.follow(params[:user_id])
@user.create_notification_follow!(current_user) #Postscript part
redirect_to request.referer
end
app/controllers/notifications_controller.rb
def index
@notifications = current_user.passive_notifications.order(created_at: :DESC)
end
app/views/notifications/index.html
<h1>Notice</h1>
<% if @notifications.exists? %>
<% @notifications.each do |notification| %>
<table>
<tr>
<td>
<%= attachment_image_tag notification.visitor, :image, size: "50x50" %>
</td>
<td>
<%= link_to user_path(notification.visitor) do %>
<%= notification.visitor.name %>
<% end %>
</td>
<td>
Followed by.
</td>
<td>
<%= " (#{time_ago_in_words(notification.created_at)}Before)" %>
</td>
</tr>
</table>
<% end %>
<% else %>
<p>There is no news</p>
<% end %>
Recommended Posts