In my last post I was asking how I could check for the existance of a
record before inserting a new one and this was the helper method that I
was using to do this:
def already_friend_of?(friend)
begin
self.friends.find(friend.id)
true
rescue
false
end
end
I was told that this is not very efficient, as it hits the db every time
I call it. I completely agree and would like to do this in a more
optimized way. I was told to create another method that reads all the
friend_id’s of my user into an array and work on that array instead. I
think this is a good approach, since I would have to hit the db just
once to get that information and then use the array from then on.
My question is… how do I go about doing that and where would my code
be? In the Model? In the Controller? In a helper file? I also need some
help writing the actual ruby code to define an array of friend_id’s.
My User model HBTM Friends. So I can call my_user.friends.find(:all) and
it will return all of his/her friends. Does my_user.friends return an
array of only those friends that belong to my_user? If so, can I just
assign that to a variable in my User model and access it in my
controllers and views?
Any help would be greatly appreciated.