包括在respond_with哈希虚拟属性 [英] Including a virtual attribute in the respond_with hash

查看:141
本文介绍了包括在respond_with哈希虚拟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包括内的respond_to JSON哈希虚拟属性/方法。

I am trying to include a virtual attribute/method within a respond_to JSON hash.

模型(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根雇员的集合,也包括了总的散列内。这种运作良好,并返回所有员工一个很好的JSON结果和总价值。

It is important that I have "data" as the json root for the collection of "employees" and also to include the "total" within the hash. This works well and returns a nice JSON result of all the employees and the total value.

我的qustion是:我如何包含虚拟属性my_method为每个员工内JSON响应员工哈希

My qustion is: How do I include the virtual attribute "my_method" for each employee within the employees hash in the JSON response?

感谢您的时间!

推荐答案

这是为我工作。

Employee.rb

def as_json(options={})
  super.as_json(options).merge({:my_method => my_method})
end

感谢cmason指着我在正确的方向。任何其他的解决方案是值得欢迎的。

Thanks for cmason for pointing me in the right direction. Any other solutions are welcome.

这篇关于包括在respond_with哈希虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆