0

Using

  result = Model.select(Model.table_name + '.*')
  result = result.select(47 AS new_column)
  result = result.where(...).order(...).limit(...) # etc.

  result.to_a # gives an array of Model instances

I need to access the new_column value as an attribute of the Model instances.

I do not want to create a calculated attribute on the model; the data must come from the constructed query. The non-database column's data must get loaded as the Model instance is getting inflated by the #to_a

I have read Incorporating Custom SELECT clause in ActiveRecord query and Return custom columns in Rails ActiveRecord Query, which looked related but are not.

ActiveRecord query with nested models and derived column values?, Access SQL computed columns through ActiveRecord, and Adding a computed column to an ActiveRecord query look like they are answering my question, but they seem to say that the extra column values from the source query are automatically attached to the model instance, and one just adds accessors to get them (or not).

I have added attr_accessor for the new columns' names to the model's class, but these attributes do not seem to be serialized when I return it as a graphQL response. Where can I find information about the actual mechanics of the AciveRecord#attributes array and how to add non-database columns to it ?

Cheers

Richard Haven
  • 1,122
  • 16
  • 31
  • Why not just build your own SQL and use `find_by_sql` which does support dynamic / ad-hoc attributes? – Cody Caughlan Mar 17 '18 at 06:31
  • Will that make the attributes serialize with graphql-ruby? I suspect it uses the attributes or columns hash to access the values, and the new columns are not on that list (even if their values are associated with the instance). I need to make them "first-class" attributes of the Model instance so the graphQL framework will recognize them – Richard Haven Mar 17 '18 at 06:37

1 Answers1

0

Sometimes, Rails really is that cool

The result of the query is part of the inflated model instance, but one needs accessors (getters) to see it.

The attributes hash has the additional columns in any case

Richard Haven
  • 1,122
  • 16
  • 31