侧边栏壁纸
  • 累计撰写 218 篇文章
  • 累计创建 59 个标签
  • 累计收到 5 条评论

as_json 方法

barwe
2021-11-18 / 0 评论 / 0 点赞 / 640 阅读 / 596 字
温馨提示:
本文最后更新于 2022-07-18,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

将查询结果集转换为哈希对象。

root

将关系名作为记录集的

## 全局配置
ActiveRecord::Base.include_root_in_json = false # default
## 即时配置
User.as_json(root: true)

only & except

限制需要哈希的属性:

User.all.as_json(only: [:id, :name])
User.all.as_json(except: [:created_at, :updated_at])

methods

将模型上定义的 get 方法包含进哈希结果中:

# 模型 User 上应该定义了 permalink 方法
User.all.as_json(methods: :permalink)

include

该参数可以将与记录相关的关系中的记录同时哈希到结果中,默认引入所有字段:

User.all.as_json(include: :posts)
#=> {"id" => 1, "name" => "barwe", "posts" => [{...}, {...}]}

include指定为哈希可以控制对关联关系的哈希方式:

User.all.as_json(include: {
    posts: {
        only: :title,
        include: [:comments, :cities]
    }
})
0

评论区