将通用字段添加到rails JSON响应(Add generic fields to rails JSON response)

编程入门 行业动态 更新时间:2024-10-24 08:28:10
将通用字段添加到rails JSON响应(Add generic fields to rails JSON response)

我需要为REST api呈现JSON响应,其中我需要包含不属于正在呈现的模型的其他JSON字段。 我确实阅读了有关ActiveModel的链接 ,它建议使用“:methods”选项调用另一个方法,我可以在其中添加其他通用字段。

def add_fields { "field1" => "true" } end if @user.save render :json => @user.as_json(:only => [:username, :org], :methods => [:add_fields]) endif

但是,当收到JSON响应时,只在JSON中返回用户名和组织字段。 不添加方法“add_fields”中定义的附加参数。 由于没有向JSON响应中添加哪些附加字段,我错过了什么。 或者是否有更好的方法在JSON响应中添加通用字段(不是模型的一部分)?

I need to render JSON response for the REST api in which I need to include additional JSON fields that are not part of the model being rendered. I did read this link about ActiveModel where it suggests to use the ":methods" option to call another method where I can additional generic fields.

def add_fields { "field1" => "true" } end if @user.save render :json => @user.as_json(:only => [:username, :org], :methods => [:add_fields]) endif

However, when the JSON response is received only the username & org fields are returned in the JSON. The additional parameters defined in the method "add_fields" are not added. What is it that I am missing due to which additional fields are not being added to JSON response. Or is there a better way to add generic fields (not part of model) in JSON response?

最满意答案

可能忘了在User中实现#add_fields方法。

May be you forgot to implement the #add_fields method in User.

更多推荐

本文发布于:2023-07-22 18:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222333.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   JSON   rails   Add   fields

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!