Forum: Ruby on Rails AR's find_by_* limits return results. How to avoid it?

1ac774797c9e79861840599b23653c3c?d=identicon&s=25 Wins Lin (zvooq)
on 2013-05-29 01:52
When I use find_by_name method I get LIMIT 1 result.

> SELECT "users".* FROM "users" WHERE "users"."age" = 25 LIMIT 1

But the "age" column is not unique in my table and its value may repeat.
So I expect that an array of records where "age" is 25 will be returned.
But AR limits the query by 1.

How to avoid it? Or is it the default behavior of "find_by_" methods to
limit queries by 1?
But it is not mentioned in Rails Guides then
72a6d1c2016a6ec343248690d4a9eb52?d=identicon&s=25 Kang Cao (Guest)
on 2013-05-29 04:55
(Received via mailing list)
You should use 'where' if you are using rails 3.  the find_by method is
not
suggested now. Hence your problem is easy to be resolved by
"User.where(:age=>25)
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2013-05-29 10:42
(Received via mailing list)
On Wednesday, May 29, 2013 12:52:51 AM UTC+1, Ruby-Forum.com User wrote:
> limit queries by 1?
> But it is not mentioned in Rails Guides then
>
>
That's correct. find_by_* returns at most one row, find_all_by_* returns
all of them

Fred
1ac774797c9e79861840599b23653c3c?d=identicon&s=25 Wins Lin (zvooq)
on 2013-05-29 15:01
Kang Cao wrote in post #1110456:
> You should use 'where' if you are using rails 3.  the find_by method is
> not suggested now. Hence your problem is easy to be resolved by
> "User.where(:age=>25)

Oh, yes, you're right. From Edge Guides:
Dynamic finders have been deprecated in Rails 4.0 and will be
removed in Rails 4.1.

I thought the other way around, that dynamic finders are better choice.
But the thing is that .find_by may return exactly a model object, but
.where returns ActiveRecord::Relation in all cases.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.