Rails Rails 提供 JSON 格式的 API,如何自定义字段呢?

v2m · January 21, 2013 · Last by dorayatou replied at June 04, 2013 · 4875 hits

比如说一个 blog 系统,一篇 blog 有很多 comment,每个 comment 有 user_id 字段,当请求一个 blog 的所有 comments 的时候,我想同时返回这个 user_id 对应 user 的详细信息(昵称,头像等),那我用 rails 要怎么写呢? 还有就是我这样每次用户获取 comments 的时候,每条 comment 都要查询用户表来获取用户的详细信息,性能上有没有什么问题?如果有的话,我应该怎么处理比较合适?

rabl or jbuilder 之类的 json 模板可以解决问题

查询性能问题可以通过缓存解决

在视图文件中可以添加对应格式的模板文件,如:comments.json.erb 等,里面想怎么写就随你便了

看这里

comment.to_json(:include => :user)

对于复杂的 json 楼上 2 位也很适用

也能在 comment.rb 中做处理

#Override
def as_json(options = {})
  if options
    super
  else
    super.merge(
      :create_time => self.created_at.to_i,
      :user => self.user
    )
  end
end

感谢 ls 各位😄

erb 模板能够按照自己选择的字段显示成 json 格式数据吗?

You need to Sign in before reply, if you don't have an account, please Sign up first.