finiteloop
finiteloop

Reputation: 493

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! :)

Upvotes: 1

Views: 3542

Answers (3)

shooma
shooma

Reputation: 495

city = Building.where(building_name: building).pick(:city)

Rails 6 introduced pick method with works like where(..).pluck(..).first. Docs

Upvotes: 0

mu is too short
mu is too short

Reputation: 434615

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.

Upvotes: 1

Josh Brody
Josh Brody

Reputation: 5363

building_city = Building.select(:city, :building_name).where(building_name: building).uniq — you need to include the building_name

Upvotes: 0

Related Questions