Reputation: 11
I am trying create notification
to add user friend
.
However, when I try to add a friend to the error.
Friendships model
class Friendship < ApplicationRecord
after_save :notification
belongs_to :user
belongs_to :friend, class_name: "User"
has_many :notification
private
def all_friendships
@all_friend = Friendship.order('created_at DESC').limit(1)
end
def notification
all_friendships.each do |friend|
Notification.create(recipient: friend.friend_id, actor: self.user, action: "add friend", notifiable: friend)
end
end
end
Friendships controller
class FriendshipsController < ApplicationController
before_action :set_friendships, only: [:show, :update, :destroy]
def index; end
def create
@friendship = current_user.friendships.build(friend_id: params[:friend_id],
accepted: false)
if @friendship.save
redirect_to current_user
else
redirect_to users_path
end
end
def update
@friendship.update_attributes(accepted: true)
if @friendship.save
redirect_to current_user
else
redirect_to users_path
end
end
def destroy
@friendship.destroy
redirect_to current_user
end
private
def set_friendships
@friendship = Friendship.where(user_id: params[:id]).or(Friendship.where(friend_id: params[:id])).first
end
end
Notification model
class Notification < ApplicationRecord
belongs_to :recipient, class_name: "User"
belongs_to :actor, class_name: "User"
belongs_to :notifiable, polymorphic: true
scope :unread, -> { where(read_at: nil) }
end
Error
ActiveRecord::AssociationTypeMismatch in FriendshipsController#create
User(#70140147575580) expected, got 2 which is an instance of Integer(#70140150807860)
Extracted source (around line #15):
def notification
all_friendships.each do |friend|
Notification.create(recipient: friend.friend_id, actor: self.user, action: "add friend", notifiable: friend)
end
end
end
Upvotes: 1
Views: 1750
Reputation: 721
You set friend_id
(Integer) instead of a user model (recipient: friend.frien_id). Need to set user model. Try:
def notification
all_friendships.each do |friend|
Notification.create(recipient: friend, actor: self.user, action: "add friend", notifiable: friend)
end
end
UPDATE: It is not good to call variable of Friendship
class friend
, as friend
should be User
.
Anyway here is the code:
def notification
all_friendships.each do |friend|
Notification.create(recipient: friend.friend, actor: self.user, action: "add friend", notifiable: friend)
end
end
Upvotes: 1