在 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
重要的是,我将“data”作为“employees”集合的 json 根,并且将“总计”包含在哈希值中。这运行良好,并返回所有员工和总价值的良好 JSON 结果。
我的问题是:如何在 JSON 响应的员工哈希中包含每个员工的虚拟属性“my_method”?
感谢您抽出时间!
I am trying to include a virtual attribute/method within a respond_to JSON hash.
The Model (employee.rb)
attr_reader :my_method
def my_method
return "foobar"
end
The Controller (employees_controller.rb)
respond_to :json
def index
@employees = Employee.all
respond_with(:data => @employees, :total => Employee.all.count)
end
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.
My qustion is: How do I include the virtual attribute "my_method" for each employee within the employees hash in the JSON response?
Thanks for your time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这对我有用。
Employee.rb
感谢 cmason 为我指明了正确的方向。欢迎任何其他解决方案。
This is what worked for me.
Employee.rb
Thanks for cmason for pointing me in the right direction. Any other solutions are welcome.
在 Rails 3 中可以使用以下
In Rails 3 one can use following
在模型中覆盖 as_json 应该可以解决问题:
Overwriting as_json in your model should do the trick: