Search code examples
postgresqlruby-on-rails-4activerecordruby-on-rails-5

Get a dynamic column value in Activerecord Select statement


I have a model named Product and I want to get the id, name and a dynamically calculated attribute value from ActiveRecord SELECT statement. Product model has id, name, product_type attributes. Currently what I am trying is using an SQL like approach

Product.select("id, name, CASE WHEN product_type = 'AB' THEN 'xyz1' WHEN product_type = 'BC' THEN 'xyz2' END AS custom_value")

Which translates to the following Raw SQL

SELECT id, name, 
  CASE 
   WHEN product_type = 'AB' THEN 'xyz1'
   WHEN product_type = 'BC' THEN 'xyz2'
  END AS custom_value
FROM Product

but this approach does not return the column computed at runtime, it only returns the id and name columns for the Product record.


Solution

  • The "product_type" column isn't explicitly in the return value, but it´s there available for using it. If you execute Product.select(...).first.case you'll see its corresponding value.

    If you want a different way to identify and access to it, you can use an alias:

    Product.select("
      id,
      name,
      CASE
        WHEN product_type = 'AB' THEN 'xyz1'
        WHEN product_type = 'BC' THEN 'xyz2'
      END AS foo
    ").first.foo
    # "xyz1"