Rails将查询从Rails 3.2.12转换为4.0.0错误

时间:2015-05-08 20:56:00

标签: ruby-on-rails ruby ruby-on-rails-4

您好我在将我的3.2.12 Rails应用程序中的convertigs Querys转换为新转换的4.2.0版本。

我明白了:

@data[:weekday] ||= Xyz.count(:include => [:membership],
          :conditions => ["xyz.done_at IS NOT NULL AND xyz.course_id = ?", @course_id],
          :group => "WEEKDAY(xyz.done_at)").collect {| val | [val[0].to_i, val[1]]}

我做了这个新的,这是一样的吗?

@data[:weekday] = Xyz.where("done_at IS NOT NULL AND memberships.course_id = ?", @course_id).joins(:membership).group("WEEKDAY(done_at)").count()

我得到了这个:

@data[:xyz_per_hours] ||= Xyz.count(:include => [:membership],
           :conditions => ["xyz.done_at IS NOT NULL AND memberships.course_id = ?",  @course_id],
           :group => "TIMESTAMPDIFF(HOUR, xyz.created_at, xyz.done_at)").to_a.select do | val |
  val[0].to_i < 120
end

我已将其转换为:

@data[:xyz_per_hours] = Xyz.where("done_at IS NOT NULL AND course_id = ?",  @course_id).joins(:membership).group("TIMESTAMPDIFF(HOUR, created_at, done_at)").count().to_a.select do | val |
    val[0].to_i < 120
  end

但我收到了这个错误:

Mysql2::Error: Column 'created_at' in field list is ambiguous: SELECT COUNT(*) AS count_all, TIMESTAMPDIFF(HOUR, created_at, done_at) AS timestampdiff_hour_created_at_done_at FROM `xyz` INNER JOIN `memberships` ON `memberships`.`id` = `xyz`.`membership_id` WHERE (done_at IS NOT NULL AND course_id = 44) GROUP BY TIMESTAMPDIFF(HOUR, created_at, done_at)

怎么了?

2 个答案:

答案 0 :(得分:1)

在小组条款

"TIMESTAMPDIFF(HOUR, created_at, done_at)"

您需要为列created_at指定一个表格,就像它在原始表达式中一样 - xyz.created_at

你的第一个问题

  

我做了这个新的,这是一样的吗?

两个表达式之间只有一个区别 - 在第一个表达式中使用:include => [:membership]表示LEFT OUTER JOINs操作(documentation),但在第二个表达式中使用joins(:membership)这意味着INNER JOIN操作

答案 1 :(得分:1)

最后一个问题发生在您的#group声明中。由于您加入了成员身份,并且成员身份和xyz都有created_at个属性,因此查询无法知道要排序的created_at