Suppose in Ruby on Rails, there is a return of JSON data:
render :json => array_of_purchases
and this array_of_purchases contains many Purchase objects, each one with a product_id
. Now if we want to add a property to the JSON returned, so that each Purchase object will also include its Product object data:
"product": { "id": 123, "name": "Chip Ahoy", image_file: "chip_ahoy.jpg", ... etc }
Then how can a new instance variable be added inside this controller action?
It might be
def get_data
# getting data ...
class Purchase
attr_accessor :product # adding an instance variable
end
array_of_purchases.each {|p| p.product = Product.find(p.product_id)}
render :json => array_of_purchases
end
but adding an instance variable to a class within this method (which is a controller action) won't work.
Update: this is assuming 1 Order has many Purchases, and 1 Purchase is a product and a quantity. (maybe some system call it an order line?)