Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Single Field with Rails Query

I'm having trouble with something that should be so easy, but I don't know what I'm doing wrong. I'm simply trying to do a query that returns a single field instead of the complete record in Rails 3.

model method

def self.find_user_username(user_id)
  user_name = User.select("user_name").where(user_id)
  return user_name
end

I'm staring at the Rails Guide ( http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields) and it simply says (where viewable_by, locked = fields):

Client.select("viewable_by, locked")

I've tried flip flopping the select, like so:

User.select("user_name").where(user_id) - AND - 
User.where(user_id).select("user_name")

but neither work. In fact, I even tried:

user_name = User.select("yoda").where(user_id)

and I didn't get an error. When I look in the view, where I have:

Friend.find_user_username(friend.user_id)

I just keep getting the hash: ActiveRecord::Relation:0x2f4942f0

like image 555
yellowreign Avatar asked Mar 03 '12 02:03

yellowreign


People also ask

What does .take do in Rails?

The Take method returns a record without any implied order. You can also specify a parameter, for example, #take(5) which will return the number of records you have specified in your parameter. If you don't care about the order or if you want an arbitrary record, #take is a good way to go.

What does pluck return in Rails?

In Rails, pluck is a shortcut to select one or more attributes without loading the corresponding records just to filter out the selected attributes. It returns an Array of attribute values.

What is eager loading in Rails?

Eager loading is a way to find objects of a certain class and a number of named associations. Here I share my thoughts on using it with Rails. What are N + 1 queries? It mainly occurs when you load the bunch of objects and then for each object you make one more query to find associated object.


2 Answers

User.where(:id => user_id).pluck(:user_name).first

Should do what you're trying to do.

pluck "accepts a column name as argument and returns an array of values of the specified column with the corresponding data type"

like image 55
Aldo 'xoen' Giambelluca Avatar answered Oct 14 '22 10:10

Aldo 'xoen' Giambelluca


Rails 6 introduced ActiveRecord::Relation#pick.

pick(:foo) is equivalent to limit(1).pluck(:foo).first.

like image 4
Janosch Avatar answered Oct 14 '22 10:10

Janosch