我正在为应用程序构建一个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's。我找到了一种方法,但它并不觉得非常干燥。感觉太重复。
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')}}}
我觉得它的可读性也不是很好。
感谢
你能否提到你用过的东西,这样你就不会得到与回复相同的方法:) – 2014-09-23 17:24:48
我想看看'as_json'方法的记录方式。 – 2014-09-23 17:25:49