Advice on Optimization, and where to put what?

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.

There are a variety of techniques you can use to perform optimizations
when
you need them. You should always wait until you have measured your
application’s performance before you perform these optimizations.

It might turn out that this functionality isn’t a big issue for your
app, in
which case, the code as written is all you need. Building your app in a
way
that allows you to isolate changes when you need to optimize is the
right
way to go. As you build your app, it may be that this method will be
removed completely, to be replaced with something different - optimizing
early is then a complete waste of time.

When you do get to the optimization phase, you should run in production
mode, with Active Record logging set to debug (not the default in
production) so you see the SQL queries in the log file. Then you’ll run
your application load against the server, see what is too slow under
load,
and work out which queries to tackle first.