AnApprentice
AnApprentice

Reputation: 111010

Rails validation to ensure a user doesn't friend themselves

I have a Friend model: user_id, friend_id, status

How can I add a validation to the friend model that prevents a user (user_id) from friending themselves (friend_id)... something like user_id does not equal friend_id?

Suggestions? Thanks

Upvotes: 2

Views: 81

Answers (1)

Brian
Brian

Reputation: 6840

Perhaps something like this will work (note: semi-pseudo code)

validates :friend, :presence => true, :unless => :friend_is_self

def friend_is_self
  user_id == friend_id ? false : true
end

This Rails Guide section may prove helpful.

Upvotes: 3

Related Questions