1

I have a User model that has all the queried fields with the existing data in the database. When I execute the following query-

@user = User.find(4, :select => 'user_fname, user_lname')

Rails throws the following error for the above line

Couldn't find all Users with 'user_id': (4, {:select=>"user_fname, user_lname"}) (found 1 results, but was looking for 2)

What's going wrong?

Achrome
  • 7,773
  • 14
  • 36
  • 45
wolf3D
  • 97
  • 1
  • 11

4 Answers4

4

You can try this. I hope this will help.

@user = User.where("id = ?", 4).select( "user_fname, user_lname")
Amit Sharma
  • 3,427
  • 2
  • 15
  • 20
3

Rails 4 : use pluck as a shortcut to select one or more attributes without loading a bunch of records just to grab the attributes you want.

Try:

> User.where(id: 4).pluck(:user_fname , :user_lname).first
#=> ["John", "Smith"] # this is just sample of output
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
0

You are using #find incorrectly. It takes IDs as arguments, not SQL. It's trying to use that second argument as an ID, which clearly won't work.

http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find

Brennan
  • 5,632
  • 2
  • 17
  • 24
  • Interestingly `User.find(4, :select => 'first_name, last_name')` works on Rails 3.2.19. It must depend on the version of Rails you're using. – nesiseka Jun 03 '15 at 20:43
  • 1
    Oh wow, I suppose I was looking at old docs. You're absolutely right – Brennan Jun 04 '15 at 02:40
0

find only finds records by id. You can pass in an array of id's but it doesn't take any options. So it thinks the hash you are passing is an id, and it bombs because it can't find a record with that ID. I think what you want is something like:

@user = User.find(4)
fname = @user.fname
lname = @user.lname
Daiku
  • 1,237
  • 11
  • 20
  • I thought maybe I could use something like this - http://stackoverflow.com/a/10256469/4630523 – wolf3D Jun 03 '15 at 20:50
  • @wolf3D If you read the comment in that SO question, you'll see "This is no longer correct and is not supported in Rails 4. Answer needs updating." .find is meant to find a single record. .where is meant to find more than one record. – aaron-coding Jun 03 '15 at 21:12
  • @aaron-coding I was using it to obtain the record of a single user. Thanks anyway! – wolf3D Jun 04 '15 at 18:58