title: Accessing virtual attribute from JSON
body: <p>My setup: Rails 2.3.10, Ruby 1.8.7</p>
  
  <p>I have experimented, without success, with trying to access a virtual attribute in a model from a JSON call. Let's say I have the following models and controller code</p>
  
  <pre><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 =&gt; @product }                                     
    end
   end
  end
  </code></pre>
  
  <p>What I like is to have the JSON output also include Product.discounted_price which is calculated in real-time for each call, ie discounted_price = Price.discount * Product.price. Is there a way to accomplish this?</p>
  
  <p><strong>SOLUTION:</strong>
  With the initial help from dmarkow, I figured it out, my actual scenario is more complex than the above example. I can do something like this, in the Product model, add a getter method</p>
  
  <pre><code>def discounted_price
   ...# do the calculation here
  end
  </code></pre>
  
  <p>In the JSON call do this </p>
  
  <pre><code>store = Store.find(1)
  store.as_json(:include =&gt; :products, :methods =&gt; :discounted_price)
  </code></pre>