best way to check if record exists? count with limit 1?

@c.friends.find_by_id params[:friend_id]

that will return nil if the user doesn't exist.

If you don't need to load the friend object into memory, sure, you could do a count instead of a find.

There's really nothing intensive about this, assuming you have indexes setup. Considering that one user should probably only be able to be friends with another user once, you can create a unique index, which will be very zippy.

Also, be on the lookout for signs that you might want to promote a Friendship to its own abstraction.

Pat

Hi Aryk,

Aryk Grosz wrote:

Isn't the best way to just test if it exists to do a count with a limit 1?

The best way would probably be to use the exists? method. I'm not sure of the exact syntax, but for a start you might try...

answer = Model.exists?(["user_id = ? and book_id = ?", 4, 7])

hth, Bill

Bill,

If you look at the code for the "exists?" function, you'll see that its really just another way of writing find :first.

That's the difference between interface and implementation. You can look at exists? and know what it does without caring how it does it.

Which leads me to ask:

Why not just use count with limit 1 instead of find with limit 1?

I just don't get it. It is no extra code to achieve the same results faster. What am I missing here?

Nothing. You're just looking way too much into this. Go ahead and use count if you really want to. Heck, you can even override AR::Base.exists? to use a count implementation instead of find, if that's what you want.

Pat