Ruby on Rails 4加入數組和哈希
我想加入一個問題數組和哈希組合在一起的問題的ID。
哈希按來自Answers的記錄的question_id屬性進行分組。
該數組包含所有問題,索引是id。
我試圖把它們放入一個數組@pdf。首先問題是枚舉索引的答案。但它表現得很奇怪。
@pdf = []
@test = Test.find(params[:id])
@test_questions = @test.questions
answers = Answer.find(:all)
@all_answers = answers.group_by(&:question_id)
@test_questions.each do |q|
@pdf << q
@pdf << @all_answers.select { |i| i == q }
end
日誌顯示此:
=> [#<Question id: 1, content: "How did the chicken cross the road?", question_type: "MC", category: "ip_voice", product_id: 8, active: true, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14", user_id: 1>, {}, #<Question id: 2, content: "Is this working?", question_type: "TF", category: "ip_voice", product_id: 6, active: true, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53", user_id: 1>, {}]
這是@all_answers:
=> {1=>[#<Answer id: 1, content: "It walked", question_id: 1, correct: false, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">, #<Answer id: 2, content: "It was thrown", question_id: 1, correct: true, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">, #<Answer id: 3, content: "It got run over and pushed", question_id: 1, correct: false, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14">], 2=>[#<Answer id: 4, content: "False", question_id: 2, correct: true, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53">, #<Answer id: 5, content: "True", question_id: 2, correct: false, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53">]}
這是@test_questions:
=> #<ActiveRecord::Associations::CollectionProxy [#<Question id: 1, content: "How did the chicken cross the road?", question_type: "MC", category: "ip_voice", product_id: 8, active: true, created_at: "2014-05-07 17:10:14", updated_at: "2014-05-07 17:10:14", user_id: 1>, #<Question id: 2, content: "Is this working?", question_type: "TF", category: "ip_voice", product_id: 6, active: true, created_at: "2014-05-13 16:10:53", updated_at: "2014-05-13 16:10:53", user_id: 1>]>
我是新來的許多軌道/ Ruby方法。
可能重複[使用Prawn使用屬於collectionproxy的值的數組創建PDF](http://stackoverflow.com/questions/23768731/create-pdf-with-arr屬於收集的代理使用蝦) –