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
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.
active record relation
Fix:
You can do
@user = User.where(code: 123).first
OR
you can use dynamic finders
dynamic finders
@user = User.find_by_code(123)
If you want to find one user with code == 123, you can use a method find_by, for example:
code == 123
find_by
@user = User.find_by(code: 123)
User, id .
User
id
EDIT: Rails 4.x, find_by_code finder:
find_by_code
where, . :
where
. , , :
, . @user.id ..
@user.id
, first, where array , ,
first
array
@user = User.where(code: 123).first id = @user.id