为Inner Join查询编写ActiveRecord关联语句

时间:2016-08-25 23:47:19

标签: mysql ruby-on-rails ruby activerecord rails-activerecord

有三个表格即出勤率,学生和科目,但我没有成功尝试使用有效记录构建内部联接查询。

所需的SQL查询

获取正确数据的原始sql语句是

SELECT * FROM attendances AS a
INNER JOIN subjects AS b ON a.subject_id = b.id
WHERE b.organization LIKE  '%city%'
AND a.started_at BETWEEN  '2016-07-11 02:59:00' AND  '2016-07-11 09:00:00'

上述查询正确提取正确的30行。但是,当我尝试使用活动记录关联执行相同操作时,会出现问题。

有效记录关联

ActiveRecord::Base.establish_connection ({ adapter: 'mysql2',host:'localhost',
username: 'testuser',password: '***',database: 'database'})  


class Subject < ActiveRecord::Base
  has_many :attendances
  has_many :students, through: :attendances
end

class Student < ActiveRecord::Base
  has_many :attendances
  has_many :subjects, through: :attendances
end

class Attendance < ActiveRecord::Base
  belongs_to :subject
  belongs_to :student
end

data = Attendance.
where(started_at:  start_date..end_date).
joins(:subject).
where(subjects: {:organization => city}).
pluck(:subject_id,:name,:duration,:started_at,:student_id)

使用_to_sql_并在删除:pluck后,由活动记录生成的sql查询是

SELECT `attendances`.* FROM `attendances` INNER JOIN `subjects` 
         ON `subjects`.`id` = `attendances`.`subject_id` 
         WHERE (`attendances`.`started_at` BETWEEN '2016-07-11 02:59:00' 
         AND '2016-07-11 09:59:00') 
         AND `subjects`.`organization` = 'city' 

将语句修改为以下语句也无济于事。

data = Attendance.joins(:subject).
where('started_at BETWEEN ? AND ?','2016-07-11 02:59:00','2016-07-11 09:59:00').
where(subjects: {:organization => 'city'}).
pluck(:subject_id,:name,:duration,:started_at,:student_id)

删除后为上述语句生成的sql查询:使用_to_sql_按照建议选择

 SELECT `attendances`.* FROM `attendances` INNER JOIN `subjects` 
 ON    `subjects`.`id` = `attendances`.`subject_id` 
 WHERE (started_at BETWEEN '2016-07-11 02:59:00' AND '2016-07-11 09:59:00') 
AND `subjects`.`organization` = 'city' 

上述活动记录语句都会导致获取其他无关紧要的行。我无法生成所需的正确sql查询,如前所示。

构建正确的活动记录语句或关联将非常有用。

环境: -

ruby 2.1.6
activerecord 4.2.4

0 个答案:

没有答案