RoR Take Attributes from ActiveRecord :: Relation

I am new to RoR. Please tell me how to take attributes from ActiveRecord :: Relation? For example, I write:

@user = User.where(code: 123)

next I want to take the id attribute

id = @user.id

but this method does not work. thanks in advance

+4
source share
4 answers

When using .where it gives active record relation, so you cannot find the identifier directly on it, because this relation is not one object of the model.

Fix:

You can do

@user = User.where(code: 123).first

OR

you can use dynamic finders

@user = User.find_by_code(123)
+2
source

If you want to find one user with code == 123, you can use a method find_by, for example:

@user = User.find_by(code: 123)

User, id .

EDIT: Rails 4.x, find_by_code finder:

@user = User.find_by_code(123)
+2

where, . :

@user = User.where(code: 123).first

. , , :

@user = User.find_by_code(123)

, . @user.id ..

0

, first, where array , ,

@user = User.where(code: 123).first
id = @user.id
0

All Articles