[SOLVED] Return Single Field with Rails Query

Issue

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

Solution

BTW if the question is about ActiveRecord::Relation it’s the class of the object returned by where and select as it’s said in the Rails Guide you’re reading.
It’s optimized to be chained between several methods and you get the model object when you actually access an element of the association (so behind the scenes the SQL query is run just one time). This means you get the Relation object because you just return it.

In this case maybe the best solution is just use find and the access the user_name attribute

def self.find_user_username(user_id)
  User.find(user_id).user_name
end

The query will get all the other attributes from the DB but you’ll return just the username.

Answered By – Aldo 'xoen' Giambelluca

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.