Whenever a notification is created how can we set the :user_id
for the user who made the comment (and in affect the notification)?
When I check rails console
for some reason all Notifications
are showing up as user_id: 1
when some of them should be user_id: 2
since the latter was the one who did the commenting.
I'm probably just not understanding the code well enough because I followed along this tutorial inputting my own version along the way.
comment.rb
class Comment < ActiveRecord::Base
after_create :create_notification
has_many :notifications
has_many :comment_likes
has_many :likers, through: :comment_likes, class_name: 'User', source: :liker
belongs_to :valuation
belongs_to :user
validates :user, presence: true
private
def create_notification # I replaced the tutorial's "Post" with my "Valuation"
@valuation = Valuation.find_by(self.valuation_id)
@user = User.find_by(@valuation.user_id).id
Notification.create(
valuation_id: self.valuation_id,
user_id: @user,
comment_id: self,
read: false
)
end
end
notifications_controller
class NotificationsController < ApplicationController
before_action :correct_user, only: [:destroy]
def index
@notifications = Notification.where(:user_id => current_user.id)
@notifications.each do |notification|
notification.update_attribute(:read, true)
end
end
def destroy
@notification = Notification.find(params[:id])
@notification.destroy
redirect_to :back
end
private
def correct_user
@notification = current_user.notifications.find_by(id: params[:id])
redirect_to root_url, notice: "Not authorized to edit this notification" if @notification.nil?
end
end
notifications/_notification
<%= link_to Comment.find_by(notification.comment_id).user.name, user_path(Comment.find_by(notification.comment_id).user.id) %> commented on <%= link_to "your value", notification_valuation_path(notification, notification.valuation_id) %>
Please let me know if you need further explanation or code to help you help me :-]
This
should be
in your migration file set:
in your controller:
becomes: