Ruby on rails 活动记录查询的干循环

Ruby on rails 活动记录查询的干循环,ruby-on-rails,ruby,json,loops,dry,Ruby On Rails,Ruby,Json,Loops,Dry,我正在为一个应用程序构建一个API,并使用下面的代码生成一些JSON Catagory.all.as_json(include: { questions: { include: :answers, only: [:title, :question_type]}}, only: :name) 返回的内容如下所示 [{"name"=>"music", "questions"=>[{"title"=>"somethings", "question_type"=>"text"

我正在为一个应用程序构建一个API,并使用下面的代码生成一些JSON

 Catagory.all.as_json(include: { questions: { include: :answers, only: [:title, :question_type]}}, only: :name)
返回的内容如下所示

[{"name"=>"music", "questions"=>[{"title"=>"somethings", "question_type"=>"text", "answers"=>[{"id"=>1, "question_id"=>1, "text"=>"something", "correct"=>true, "created_at"=>Mon, 22 Sep 2014 22:19:15 UTC +00:00, "updated_at"=>Mon, 22 Sep 2014 22:19:15 UTC +00:00}, {"id"=>2, "question_id"=>1, "text"=>"something", "correct"=>true, "created_at"=>Tue, 23 Sep 2014 16:01:40 UTC +00:00, "updated_at"=>Tue, 23 Sep 2014 16:01:40 UTC +00:00}]}]}]
这很好,但我想删除“created_at”、“updated_at”和ID。我找到了一种方法,但感觉不太干。感觉太重复了

Catagory.all.as_json(include: { questions: { include: :answers, only: [:title, :question_type]}}, only: :name).each {|a| a['questions'].each {|w| w['answers'].each {|f| f.delete('created_at')}}}.each {|c| c['questions'].each {|y| y['answers'].each {|b| b.delete('updated_at')}}}.each {|l| l['questions'].each {|x| x['answers'].each {|z| z.delete('id')}}}.each {|g| g['questions'].each {|h| h['answers'].each {|r| r.delete('question_id')}}}
我发现它的可读性也不是很好


谢谢

你走在正确的道路上,我不知道你为什么自己没有弄明白这一点。您可以将查询更改为:

Catagory.all.as_json(include: { questions: { include: { answers: { only: [:question_id, :text, :correct]} }, only: [:title, :question_type]}}, only: :name)

如果你经常使用这个查询,那么请把它放在
类别
类的范围内。

你能提到你使用了什么吗,这样你就不会得到与回复相同的方法:)我想看看json的方法在哪里也有文档记录。这个方法我从未见过+1Ok。。我向FB发送了与您保持联系的请求。:-@Surya谢谢,我一直试图只玩
部分,但无法解决。优秀:)