2014-09-23 152 views
1

我正在爲應用程序構建一個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')}}} 

我覺得它的可讀性也不是很好。

感謝

+0

你能否提到你用過的東西,這樣你就不會得到與回覆相同的方法:) – 2014-09-23 17:24:48

+0

我想看看'as_json'方法的記錄方式。 – 2014-09-23 17:25:49

回答

2

你是在正確的道路上,我不知道你爲什麼不知道這出自己。您可以將您的查詢改成這樣:

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

如果你正在使用此查詢頻繁,那麼請把它放在一個範圍內的內部Category類。

+0

這種方法我從來沒有見過。 +1 – 2014-09-23 18:18:22

+0

好的。我向FB發送你的請求,保持聯繫。:-) – 2014-09-23 18:36:58

+0

哈哈..當然。 :) – Surya 2014-09-23 18:38:57