Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 联接子模型结果项的查询多次错误显示_Ruby On Rails_Ruby On Rails 3_Rails Models - Fatal编程技术网

Ruby on rails 联接子模型结果项的查询多次错误显示

Ruby on rails 联接子模型结果项的查询多次错误显示,ruby-on-rails,ruby-on-rails-3,rails-models,Ruby On Rails,Ruby On Rails 3,Rails Models,我有以下模型,每个模型都是前一个模型的相关子模型,为了简洁起见,我排除了其他模型方法和声明: class Course < ActiveRecord::Base has_many :questions scope :most_answered, joins(:questions).order('questions.answers_count DESC') #this is the query causing issues end class Question <

我有以下模型,每个模型都是前一个模型的相关子模型,为了简洁起见,我排除了其他模型方法和声明:

class Course < ActiveRecord::Base 
  has_many :questions

  scope :most_answered, joins(:questions).order('questions.answers_count DESC') #this is the query causing issues  
end 

class Question < ActiveRecord::Base 
  belongs_to :course, :counter_cache => true
  has_many: :answers

end 

class Answer < ActiveRecord::Base 
  belongs_to :question, :counter_cache => true
end

现在我只填充了一个课程,所以当我在控制台中运行Course.all.count时,我得到1。第一门课程目前有三个问题,但当我运行Course.most_answered.count most_answered是我在课程中编写的scope方法,如上所示,我在console中得到3作为结果,这是不正确的。我已经尝试了查询的各种迭代,并查阅了相关资料,但似乎无法找出我做错了什么。提前感谢。

据我所知,您回答最多的范围是尝试按问题的总数排序。回答数

事实上,没有求和,因为第一门课有三个答案,你加入到这个表中会产生三个结果

您需要执行以下操作:

scope :most_answered, joins(:questions).order('questions.answers_count DESC')
  .select("courses.id, courses.name, ..., SUM(questions.answers_count) as answers_count")
  .group("courses.id, courses.name, ...")
  .order("answers_count DESC")
您需要明确指定要选择的课程字段,以便在GROUPBY子句中使用它们

编辑:


两个我提到courses.id、courses.name的地方。。。在“选择”和“组”中,需要将其替换为要选择的实际列。由于这是一个范围,最好选择课程表中的所有字段,但您需要单独指定它们。

谢谢!第一部分,你解释了为什么它会导致重复,这一点特别有用。我复制了代码,得到了一个语法错误,我把它添加到了问题的主体中。再次感谢您的帮助。我尝试通过确保小东西不会导致错误来取得一些进展,例如从复数改为单数,或者去掉某些元素,看看它是否至少能够呈现视图。不幸的是,由于我对编写查询非常陌生,这些东西并没有帮助。。再次感谢。我已经更新了答案,以澄清我的意思-的。。。用于表示需要添加到select子句中的字段。非常好,很高兴听到这个消息: