1

我有一个需要输出自定义 json 响应的 rails 应用程序。

我有一个Post模型,其中有很多statuses. 的statusapost对于每个user.

我想以Post.alljson 的形式返回,其中每个post包含与用户相关的statuses 作为常规属性(看起来它们属于的属性post,没有嵌套)

我该怎么做?我不想将 current_user 方法传递给我的模型,也不想使用序列化程序。

无论如何我可以做这样的事情:

respond_with(posts: @posts.as_json(:methods => [:status(current_user)])
#NOTE the current user arg

编辑:

澄清,我想要:

id: 1, content: 'this is a post', status: 'reviewed'
#as json of course

任何帮助表示赞赏。

4

1 回答 1

0

我通过将以下内容添加到我的 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

在我可以访问的控制器中自定义的所有 jsoncurrent_user

于 2013-11-03T07:19:10.887 回答