【问题标题】:Rails as_json, adding a custom attribute without a serializer gemRails as_json,添加没有序列化程序 gem 的自定义属性
【发布时间】:2013-11-02 23:50:42
【问题描述】:

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

我有一个 Post 模型,其中有许多 statusespoststatus 对于每个 user 都是不同的。

我想将 Post.all 作为 json 返回,每个 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

感谢任何帮助。

【问题讨论】:

  • 我可以这样做吗:@posts= Post.all(include: :statuses, conditions: { statuses: {user_id: current_user.id}})
  • 上面的评论是嵌套的,我更喜欢不嵌套的。上面没有显示所有帖子,但每个帖子都有状态记录。相反,它返回具有当前用户状态记录的每个帖子
  • 也许在Post上写一个status_for_current_user方法?
  • 类似return statuses.where(:user_id => current_user.id)

标签: ruby-on-rails json rendering overriding


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2015-04-15
    • 1970-01-01
    相关资源
    最近更新 更多