Reputation: 3012
I have users table and polls table. Assume the tables are quite big, which query would be more efficient in Rails:
User.find(user_id).polls.where('category = ?',category)
Poll.where('user_id = ? AND category = ?',user_id,category)
You may assume a user can't have too many polls(maybe in average 100 polls). And user_id and category are both indexed
Upvotes: 1
Views: 156
Reputation: 434615
The first one is equivalent to this:
user = User.find(user_id)
polls = user.polls.where(:category => category)
The User.find
will issue a
select * from users where id = ?
and then the user.polls.where(...)
part will do a:
select * from polls where user_id = ? and category = ?
Oddly enough, that's exactly what the plain Poll.where(...)
will do.
So the second should be quicker since it doesn't do the select ... from users
. OTOH, if you already have the user then user.polls.where(...)
would probably make more sense.
Upvotes: 1