0
poll_answers = PollAnswer.joins(:poll_answer_variant => {:poll_question => :poll}).select("count(poll_answers.user_id) as submits_count, poll_answers.poll_question_id").where("polls.id = 105").group("poll_questions.id, poll_answer_variants.id")

grouped = poll_answers.group_by(&:poll_question_id)

grouped[81].inject{|sum, answer_variant| sum += answer_variant.submits_count}

after what i get:

NoMethodError: undefined method `+' for #<PollAnswer poll_question_id: 81, poll_answer_variant_id: 9>
from /Users/s/.rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.7/lib/active_model/attribute_methods.rb:407:in `method_missing'
from /Users/s/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.7/lib/active_record/attribute_methods.rb:149:in `method_missing'
from (irb):926:in `block in irb_binding'
from (irb):926:in `each'
from (irb):926:in `inject'
from (irb):926
from /Users/s/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.7/lib/rails/commands/console.rb:47:in `start'
from /Users/s/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.7/lib/rails/commands/console.rb:8:in `start'
from /Users/s/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.7/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

It must be because of my virtual select count is not described like a model attribute? How can i fix that? thx

4

2 回答 2

2

来自注入的文档:“如果您没有明确指定备忘录的初始值,则使用集合的第一个元素作为备忘录的初始值。” 所以第一次通过循环,sum 的值是一个 PollAnswer 对象。您需要初始化总和:

grouped[81].inject(0){|sum, answer_variant| sum += answer_variant.submits_count}
于 2012-10-21T19:19:53.423 回答
0

当您Enumerable#inject不带参数使用时,您的块将在第一次迭代时接收前两个元素,然后是前一次迭代的结果和第三个元素,等等。

你可以传递一个参数来#inject告诉他用你选择的值和第一个元素调用你的块,然后是结果和第二个,等等。

在您的情况下(请注意我使用+而不是+=):

grouped[81].inject(0) do |sum, answer_variant|
  sum + answer_variant.submits_count
end

有关如何使用Enumerable#inject.

于 2012-10-21T19:22:19.147 回答