[英]Rails as_json, adding a custom attribute without a serializer gem
I have a rails application which needs to output a custom json response. 我有一个Rails应用程序,需要输出一个自定义json响应。
I have a Post
model which has many statuses
. 我有一个具有许多
statuses
的Post
模型。 The status
of a post
is different for every user
. 每个
user
的post
status
都不一样。
I want to return Post.all
as json with every post
containing the user-dependent status
es as regular attributes (attributes which seem like they belong to post
, nothing nested) 我想回到
Post.all
与每一个为JSON post
含依赖于用户的status
ES作为常规属性(这看起来像他们属于属性post
,没有嵌套)
How would I do this? 我该怎么做? I do not want to pass the current_user method to my model and I also do not want to use a serializer.
我不想将current_user方法传递给我的模型,也不想使用序列化器。
Is there anyway I could do something like this: 无论如何,我可以做这样的事情:
respond_with(posts: @posts.as_json(:methods => [:status(current_user)])
#NOTE the current user arg
clarification, I want: 澄清一下,我要:
id: 1, content: 'this is a post', status: 'reviewed'
#as json of course
Any help is appreciated. 任何帮助表示赞赏。
I solved this by adding the following to my PostsController: 我通过在PostsController中添加以下内容来解决此问题:
def json_params_for(objects)
collection = objects.map do |post|
{ id: post.id,
content: post.content,
created_at: post.created_at,
status: "reviewed
}
end
collection.to_json
end
all json customized within my controller where I can access current_user
我可以在其中访问
current_user
控制器中自定义的所有json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.