且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

嵌套 :json 包含在 Rails 中

更新时间:2023-01-12 17:55:12

参考 ActiveModel::Serializers::JSON#as_json 查看可以传递给 render :json 的选项.去引用:

Refer to ActiveModel::Serializers::JSON#as_json to see the options you can pass to render :json. To quote:

要包含关联,请使用 :include ...

To include associations use :include ...

二级和更高级别的关联也能正常工作:

Second level and higher order associations work as well:

user.as_json(:include => { :posts => {
                             :include => { :comments => {
                                             :only => :body } },
                             :only => :title } })
# => { "id": 1, "name": "Konata Izumi", "age": 16,
#      "created_at": "2006/08/01", "awesome": true,
#      "posts": [ { "comments": [ { "body": "1st post!" }, { "body": "Second!" } ],
#                   "title": "Welcome to the weblog" },
#                 { "comments": [ {"body": "Don't think too hard" } ],
#                   "title": "So I was thinking" } ]
#    }

没有必要直接调用 to_jsonas_json,因为 render :json 会自动执行.

It's not necessary to call to_json or as_json directly, as render :json does it automatically.