How to find a record by id and select few columns, ruby on rails?

为君一笑 提交于 2019-12-24 15:13:15

问题


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?


回答1:


You can try this. I hope this will help.

@user = User.where("id = ?", 4).select( "user_fname, user_lname")



回答2:


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



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/30630028/how-to-find-a-record-by-id-and-select-few-columns-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!