Ruby on Rails: Class.where(...) but return just 1 record?
I got a table named users, and I'm doing
array = User.where("username=?", username)
to get the user for a specific username.
My minor gripe is that this return开发者_运维百科s an array, and I have to do array[0]
but there should always be just 1 user returned.
Is there anyway, syntactically to specify that I expect just 1 record, and it shouldn't be an array returned, just the user?
You can limit it to one result:
User.where("username = ?", username).first
However, you might just want to use the dynamic find_by_
method:
User.find_by_username(username)
Also you can use the limit in the case you want to get more results, but limiting.
User.where("username = ?", username).order('created_at DESC').limit(5)
Here is another syntax to find the first record
array = User.find(:first,:conditions => {:username => username})
精彩评论