在respond_with哈希中包含虚拟属性
我试图在respond_to JSON哈希中包含一个虚拟属性/方法。
模型(employee.rb)
attr_reader :my_method def my_method return "foobar" end
控制器(employees_controller.rb)
respond_to :json def index @employees = Employee.all respond_with(:data => @employees, :total => Employee.all.count) end
重要的是,我将“数据”作为“雇员”集合的json根,并在散列中包含“total”。 这很有效,并返回所有员工和总价值的良好JSON结果。
我的问题是:如何在JSON响应中为员工哈希中的每个员工包含虚拟属性“my_method”?
谢谢你的时间!
这对我有用。
Employee.rb
def as_json(options={}) super.as_json(options).merge({:my_method => my_method}) end
感谢cmason指出我正确的方向。 欢迎任何其他解决方案。
在Rails 3中,可以使用以下内容
@yourmodel.to_json(methods: ['virtual_attr1', 'virtual_attr2']
在模型中覆盖as_json应该可以解决问题:
def as_json(options={}) { :methods=>[:my_method] }.merge(options) end