Ammar Alammar
Ammar Alammar

Reputation: 313

Correct way to find models by their association

Both of these produce the same result:

User.where(account: 1)
User.where(account_id: 1)

But the generated SQL is different:

/* User.where(account: 1) */
SELECT "users".* FROM "users" WHERE "users"."account_id" = 1

/* User.where(account_id: 1) */
SELECT "users".* FROM "users" WHERE "users"."account_id" = $1  [["account_id", 1]]

Also both of these generate the same SQL as the first version:

a = Account.find(1)
User.where(account: a)
User.where(account_id: a)
# SELECT "users".* FROM "users" WHERE "users"."account_id" = 1

So which is the correct way to find a model by its association? Is the second version safer than the first? I tried to search for what's happening at the SQL level in the second version but I coudn't find anything.

Upvotes: 1

Views: 47

Answers (1)

Dmitry Sokurenko
Dmitry Sokurenko

Reputation: 6132

There is no significant difference in your case. But if the account association is polymorphic, e.g. when there is a Business account and a Personal account, then the where(account: a) will generate something like WHERE account_type = 'Business' AND account_id = '123', while where(account_id: a) will generate just the WHERE account_id = '123'.

Upvotes: 2

Related Questions