Reputation: 851
I have a friendships model, friendships is a join table that contains a user_id
a friend_id
and a status (which is a string). In the create method for the friendship I need to do some validation and check that a friendship doesn't exist already between that user and that friend
to do this I've called:
unless userID == friendID or Friendship.exists?(userID, friendID)
However exists? throws this error when create is called:
ArgumentError (wrong number of arguments (2 for 0..1)):
I can't correctly do the validation without checking the userID
and friendID
exist in one friendship. My question is is there a better way I can do this not using exists? or is there a way I can pass two parameters to the exists? method in rails.
Thanks for any help or advice.
Upvotes: 0
Views: 1448
Reputation: 9443
You can use rails validation methods to do this.
class Friendship < ActiveRecord::Base
# ensure that user/friend combo does not already exist
validates :user, uniqueness: { scope: friend }
# ensure that friend != user
validate :friend_is_not_user
# other Friendship model code
def friend_is_not_user
if self.friend == self.user
errors.add(:user, 'cannot be friends with his or her self.')
end
end
end
Upvotes: 0
Reputation: 2129
@userid = any_user_id
@friendid = any_friend_id
(@userid == @friendid || Friendship.where(user_id: @userid,friend_id: @friendid).present?) ? true : false
OR if you want to use exists?
:
(@userid == @friendid || Friendship.exists?(user_id: @userid,friend_id: @friendid)) ? true : false
this will do exactly what you need.
Upvotes: 1