Search code examples
sqlruby-on-railsrubyruby-on-rails-4activerecord

Ruby on Rails ActiveRecord query select only column string field value with where clause?


I was wondering if there is a way to use a select statement with a where clause similar to this way that does not seem to work for me in Ruby version 2.0/Rails 4.0 trying to retrieve a single record string value of a city where the building name is a certain name:

building_city = Building.select(:city).where(building_name: building).uniq

I have also tried:

building_city = Building.select(:city).where(building_name: building).distinct

Currently I have my code working like this:

building_city = Building.where(building_name: building).first

This grabs an entire Building object, and then I can call the city by doing a:

building_city.city

This works fine with what I am trying to achieve, but I was wondering if there is a smarter way to do this. Specifically, I was wondering if there is a way to grab only the string value of a city where the building name equals a certain building and store it into a variable?

Any help/advice is greatly appreciated! :)


Solution

  • Are you perhaps looking for pluck? Something like:

    cities = Building.where(building_name: building).uniq.pluck(:city)
    

    That will perform this SQL:

    select distinct city from buildings where building_name = '...'
    

    and give you the cities as an array of strings. You'll still get an array but a quick first call will take care of that if you're certain that there will only be one entry.