Return user request to activerecord

I have a query that does some math and returns a computed custom select box with a set of results. I cannot figure out how to access this activerecord object that is being returned. I also added attr_accessor for it.

attr_accessor :percentage_used select('gateways.*, (num_transactions_today/ SUM(num_transactions_today)) AS percentage_used ').joins(:gateway_groups).where('map_gateway_groups.gateway_group_id = ?', gateway_group_id) 

in the result set, I expect to access: percent_used, but it is not there. Any ideas on what I'm doing wrong? I have never had to do this before.

thanks

+6
source share
2 answers

You can access it as

 object["percentage_used"] 
+9
source

You do not need and do not need attr_accessor . attr_accessor creates an instance variable, an access method to get the value of this instance variable, and a mutator method to change its value. When you say this:

 select('gateways.*, (num_transactions_today/ SUM(num_transactions_today)) AS percentage_used ... 

ActiveRecord will automatically add the percentage_used method to the returned objects. But the percentage_used method to access this value will be added method_missing . Since you said attr_accessor :percentage_used , method_missing will never be called, and you cannot get the value of percentage_used from the request in the usual way.

If you release attr_accessor :percentage_used , you can call percentage_used on the objects returned by this select , and you will find the values ​​you need. However, AR will not be able to convert the value to its own Ruby number, so you will have to_f return the string yourself.

+4
source

Source: https://habr.com/ru/post/952538/


All Articles