开发者

How to get attribue in the to_json attribute

I am using Rails 3 and here is my model

class LineItem < ActiveRecord::Base
  attr_reader :price
  belongs_to :product
   def price
    self.product.price * self.quantity
  end

  def as_json(options = {})
    super(:include => [:product])
  end
end

Above code works. However now I want my jso开发者_运维百科n to also have value for price in addition to the other values that I am getting.

How do I accomplish that?


You can use :methods:

def as_json(options = {})
    super(options.merge(:include => [:product], :methods => [:price]))
end

You might want to pay proper attention to any incoming :include and :method settings in your options though. So you might want to use the block form of merge:

EXTRAS = { :include => [:product], :methods => [:price] }
def as_json(options = { })
    super(options.merge(EXTRAS) { |k,ov,nv| ov.is_a?(Array) ? ov + nv : nv }
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜