Access virtual attribute from JSON

My setup: Rails 2.3.10, Ruby 1.8.7

I experimented, but to no avail, with an attempt to access the virtual attribute in the model from a JSON call. Say I have the following models and controller code

class Product
 name,
 description,
 price,
 attr_accessor :discounted_price 
end

class Price
 discount
end

class ProductsController
 def show
  @product = Product.find(params[:id])
  respond_to do |format|
   format.html # show.html.erb
   format.json { render :json => @product }                                     
  end
 end
end

I like the JSON output to also include Product.discounted_price, which is calculated in real time for each call, i.e. discounted_price = Price.discount * Product.price. Is there any way to do this?

SOLUTION: With the initial help of dmarkow, I realized my actual scenario is more complex than the above example. I can do something similar in the product model, add the getter method

def discounted_price
 ...# do the calculation here
end

In JSON call do this

store = Store.find(1)
store.as_json(:include => :products, :methods => :discounted_price)
+3
source share
2 answers

to_json :methods, .

render :json => @product.to_json(:methods => :discounted_price)
+25
0

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


All Articles