【发布时间】:2014-07-10 13:38:07
【问题描述】:
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>]>
我是许多 Rails/Ruby 方法的新手。
【问题讨论】:
标签: ruby-on-rails ruby arrays ruby-on-rails-4 hash