Home > Software engineering >  How to select a value from a hash in a query using select in ruby
How to select a value from a hash in a query using select in ruby

Time:08-04

I have a model called RealEstate, this model have some attributes like id, name, status and data (data is a hash with multiple values)

#<RealEstate id: 2629, name: "Casa en venta en La Castellana de 207m²", status: "active", data: {"area"=>false, "price"=>false, "images"=>false, "is_rent"=>false, "picture"=>false}>

I'm doing a query of real estates who are active, but I only want to bring the area from data and name, so I use select, but I do not know who to get only one value from data. What I do is the following:

real_estate.select(:name, :data)

Being real_estate a query with multiple models of RealEstate. Is there a way to get in the select only the area? Maybe something like this:

real_estate.select(:name, "data -> 'area'")

CodePudding user response:

RealEstate
  .where(status: "active")
  .pluck(:name, Arel.sql("data->'area'"))

Or just "data->'area'" instead of Arel.sql

This query will filter only active status and return array of names / areas

If you want ActiveRecord relation instead of array:

RealEstate
  .where(status: "active")
  .select(:name, "data->'area' as area")

(this way you can apply area method to relation members)

  • Related