matiit
matiit

Reputation: 8017

ActiveRecord where returns ActiveRecord::Relation

u = User.where("name = ?", "mateusz").limit(1)
u.class
=> ActiveRecord::Relation

So I cant do smth like u.email and so on. .find does right, returns User object. Is there any chance to get an User object from ActiveRecord::Relation object?

Upvotes: 4

Views: 4802

Answers (2)

Bryan Ash
Bryan Ash

Reputation: 4489

If you expect to only find one record, you could use find_by:

u = User.find_by(name: 'mateusz')

Upvotes: 3

alex.zherdev
alex.zherdev

Reputation: 24164

You should call first or last on the ActiveRecord::Relation object:

u = User.where("name = ?", "mateusz").first

Upvotes: 9

Related Questions