Rails连接表上的SQL查询

时间:2016-01-20 01:21:32

标签: mysql ruby-on-rails activerecord

我有一个带有以下型号的rails应用程序:

class Partner < ActiveRecord::Base
  has_many :timesheets
  has_many :timeslots, through: :timesheets
  # ...
end

class Timeslot < ActiveRecord::Base
  has_many :timesheets
  has_many :partners, through: :timesheets
  # ...
end

class Timesheet < ActiveRecord::Base
  belongs_to :partner
  belongs_to :timeslot
  # ...
end

请注意Timesheet如何作为存储Partner-Timeslot对的各种连接表。我希望得到所有这些合作伙伴 - 时间段对,其中时间段满足某些条件。我根本不关心此查询的Timesheet对象。我已经知道适当的SQL就是这样的:

SELECT partners.*, timeslots.*
FROM timesheets
  JOIN partners
    ON timesheets.partner_id = partners.id
  JOIN timeslots
    ON timesheets.timeslot_id = timeslots.id
WHERE (...some condition logic that I can figure out on my own...)

请注意,虽然我查询时间表表格,但实际上只需要合作伙伴和时间段对象。

你能用Rails做到吗?

有更好的方法吗?

其他信息:

我使用MySQL作为数据库

1 个答案:

答案 0 :(得分:1)

是的,你当然可以在Rails中这样做。你可以从:

开始
partner_timeslots = Partner.joins([ timesheets: :timeslot ]).select('partners.*, timeslots.*')

这将生成以下查询:

select partners.*, timeslots.* 
from partners 
  inner join timesheets on timesheets.partner_id = partners.id 
  inner join timeslots on timeslots.id = timesheets.timeslot_id

如果尝试使用控制台,请尝试partner_timeslots.to_yaml查看返回的所有partnerstimeslots属性。