我需要为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]) endifHowever, 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.
更多推荐
发布评论