计数儿童的范围has_many关系

时间:2013-04-25 02:42:00

标签: sql ruby-on-rails-3 scope

我有两个型号

# == Schema Information
#
# Table name: answers
#
#  id          :integer          not null, primary key
#  content     :text
#  question_id :integer
#  accept      :boolean
#  created_at  :datetime         not null
#  updated_at  :datetime         not null    
#  user_id     :integer
#

class Answer < ActiveRecord::Base
  attr_accessible :accept, :content, :question_id, :user
  belongs_to :question
  belongs_to :user
  delegate :username, to: :user, allow_nil: true, prefix: 'owner'
end

和问题

# == Schema Information
#
# Table name: questions
#
#  id           :integer          not null, primary key
#  title        :string(255)
#  content      :text             default(""), not null
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#  user_id      :integer
#  viewed_count :integer          default(0)
#

class Question < ActiveRecord::Base

  validates_presence_of :title, :content, :user
  attr_accessible :content, :title, :tag_list
  acts_as_taggable
  belongs_to :user, :counter_cache => true
  has_many :answers
  delegate :username, to: :user, allow_nil: true, prefix: 'owner'
  scope :owner, joins(:user)
  scope :without_answer, joins(:answers).
     select('questions.id').
     group('questions.id').
     having('count(answers.id) = 0')

  validate :validation_of_tag_list

  def self.no_answer
    Question.all.select{|question|question.answers.count == 0}
  end

范围without_answer和类方法no_answer理论上应该相同。但是,我在控制台中运行它们如下:

Loading development environment (Rails 3.2.13)
irb(main):001:0> Question.without_answer
  Question Load (0.6ms)  SELECT questions.id FROM `questions` INNER JOIN `answers` ON `answers`.`question_id` = `questions`.`id` GROUP BY questions.id HAVING count(answers.id) = 0
=> []
irb(main):002:0> Question.no_answer
  Question Load (0.6ms)  SELECT `questions`.* FROM `questions` 
   (0.5ms)  SELECT COUNT(*) FROM `answers` WHERE `answers`.`question_id` = 1
   (0.4ms)  SELECT COUNT(*) FROM `answers` WHERE `answers`.`question_id` = 2
   (0.4ms)  SELECT COUNT(*) FROM `answers` WHERE `answers`.`question_id` = 16
   (0.4ms)  SELECT COUNT(*) FROM `answers` WHERE `answers`.`question_id` = 17
   (0.3ms)  SELECT COUNT(*) FROM `answers` WHERE `answers`.`question_id` = 34
=> [#<Question id: 2, title: "Here is the second", content: "here you go\r\n", created_at: "2013-04-20 00:34:15", updated_at: "2013-04-20 00:34:15", user_id: nil, viewed_count: 0>, #<Question id: 16, title: "my question", content: "Here is my question", created_at: "2013-04-21 02:02:47", updated_at: "2013-04-23 02:29:27", user_id: 1, viewed_count: 1>, #<Question id: 17, title: "Hello", content: "me", created_at: "2013-04-23 00:37:56", updated_at: "2013-04-23 00:37:56", user_id: nil, viewed_count: 0>, #<Question id: 34, title: "Question title", content: "question content", created_at: "2013-04-23 04:57:49", updated_at: "2013-04-23 04:57:49", user_id: 42, viewed_count: 0>]
  1. 为什么范围不能按预期工作?
  2. 哪种方式会更好地应对这种情况甚至更好的解决方案?

1 个答案:

答案 0 :(得分:7)

您的without_answer范围非常接近,但需要像这样的外部联接:

scope :without_answer,
   joins('LEFT OUTER JOIN answers ON answers.question_id = questions.id').
   select('questions.id').
   group('questions.id').
   having('count(answers.id) = 0')

然后,您可以使用length获取计数:

Question.without_answer.length

注意:如果您希望without_answerno_answer相同(即返回实际的问题对象),则需要删除select

一种更简单,更快速的方法来计算未回答的问题是这样的:

Question.joins('LEFT OUTER JOIN answers ON answers.question_id = questions.id').
         where('answers.id' => nil).count

此外,这将按原样返回no_answer,只需使用all代替count

相关问题