I have a User model who HBTM Friends (class User). I would like to check for the existance of a user in the friends table before actually adding them (in case they were already added as a friend.) I have a method called already_friend_of?(friend) defined in my User model, but I am not sure how to define this method. I simply want to check to see if one user is already a friend of another user (I also use this method in my views to change the state of some links and buttons - for example, the ''add friend'' button becomes ''remove friend''.) My method currently looks like this, but it doesn''t seem to be working... def already_friend_of?(friend) begin self.friends.find(friend) true rescue false end end I appreciate any hints you can give me regarding this matter. Thank you, Ramin -- Posted via http://www.ruby-forum.com/.
def already_friend_of?(friend) begin self.friends.find(friend.id) true rescue false end end I think this is going to be very expensive because you''re calling this method on many pages (and more times per page). If you are just checking whether the current (logged in) user has this friend, you''d better create a method that gets a list of id''s from the database. These id''s are the id''s of her friends. Then the check method will be: def friend_of?(friend) @friend_ids.include?(friend.id) end And you would need a method like load_friend_ids that populates the @friend_ids array. Jules -- Posted via http://www.ruby-forum.com/.
Thank you Jules. I just forgot the .id part it seems. I will also take your advice on using the array of id''s .. i did feel like it was an expensive call, but wasn''t sure how to go about it. thanks again. -- Posted via http://www.ruby-forum.com/.
Possibly Parallel Threads
- Advice on Optimization, and where to put what?
- Isn't there any performance issue when saving serialized attributes every time?
- ActiveRecord::AssociationTypeMismatch (User(#54754560) expected, got User(#54510280))
- SwitchTower rake deply failure on DreamHost
- Simple active record issue. I must be missing something.