alphons
alphons

Reputation: 67

i need to get a user id from a query result

am querying from my User table using the user name, how do i get the user id from the query object User.where(user_name: "john")

my goal is to get the User id: 5, i thought it was as easy as (.id), but thats not working

=> #<ActiveRecord::Relation [#<User id: 5, user_name: "john", user_city: "India", created_at: "2019-01-19 18:02:32", updated_at: "2019-01-19 18:02:32">]> 

Upvotes: 1

Views: 926

Answers (2)

Justin P.
Justin P.

Reputation: 31

If you're really only trying to get the id (i.e., not using any other attributes of the object) it's usually better to formulate this as a .pluck. This requires less time for ActiveRecord to instantiate, and makes the query job take better use of your database indices. As long as User#user_name is unique (and I'd hope so!) it will return an array of length 1.

User.where(user_name: "John").first.&id 
   # SELECT "users".* FROM "users" WHERE "users"."user_name" = "John" 
   # ORDER BY "users" ASC LIMIT 1
   # => 1 or nil

User.where(user_name: "John").pluck(:id).first
   # SELECT "users"."id" FROM "users" WHERE "users"."user_name" = "John"
   # => 1 or nil

Unfortunately, find_by and its helpers don't work this way with pluck, and both of these statements instead result in errors

User.find_by(user_name: "John").pluck(:id)
User.find_by_user_name("John").pluck(:id)

Upvotes: 2

Fabio
Fabio

Reputation: 32445

Materialized where will return a collection, so you can get first record with .first

User.where(:user_name => "john").first&.id

Or use find_by which will return first record which satisfies condition.

User.find_by(:user_name => "john")&.id

Upvotes: 4

Related Questions