ruby on rails - How do I get several attributes value and method value from an ActiveRecord model? -
to solve problem, set fictitious car model below:
car model has
3 attributes(id, car_name, owner_name) and
2 methods return integers(riders, passengers).
i want one hash has values of 2 attributes , 2 methods of cars. solve problem, temporary solution below:
json_format = car.all.to_json(only: [:car_name, :owner_name], methods: [:riders, :passengers]) final_hash = activesupport::json.decode(json_format)
this works, bad because use 'to_json' method optional function.
other choice getting 1 hash directly car model via own optional function?
use as_json
. it's to_json
uses under hood, , accepts same options returns hash
.
Comments
Post a Comment