Let's say that I'm looking for a specific item in a has_many association.
Is there a way to find that won't rehit the database if what I'm requesting is already cached?
Here's my situation (which is not working and does not do what I requested):
class User
has_many :friendships
def some_function(buddy)
f = friendships.detect{|friendship| friendship.user == self &&
friendship.friend == buddy}
f.do_something
end
end
The function is susceptible to N+1 problems, but most of the time I will already have either used :include or preloaded the user's friendships elsewhere. However, if I didn't do this, then this current function will fall back to requesting all the friendships, even though it only needs one. The solution would seem to be something like this:
f = Friendship.find_by_user_id_and_friend_id id, buddy.id
However, this will hit the database again even if all the friendships are cached and I have what I need right there.
Is there any way to either use the cached copy, or if none is available, search a specific record?