2016-01-20 106 views
1

我已經在MySQLMySQL的加入查詢Ruby on Rails的

SELECT c.*, r.* 
FROM court c 
LEFT JOIN reservations r 
     ON c.`id` = r.`court_id` 
    AND `start_time` < '2016-01-20 11:30:00' 
    AND `end_time` > '2016-01-20 11:00:00' 
WHERE `start_time` IS NULL; 

連接查詢參考:

reservations.rb 
belongs_to court 
fields: start_time,end_time, court_id 

courts.rb 
has_many reservations 
fields: id, name 

我試圖將其轉換爲軌道,但似乎無法做到這一點。 我試過Courts.join(:reservations).on("start_time<'2016-01-20 11:00:00'") 但這不起作用

回答

0

轉換後的版本將是:

Courts.joins('LEFT JOIN reservations ON courts.id = reservations.id') 
     .where('reservations.start_time < ? AND reservations.end_time > ?', '2016-01-20 11:30:00', '2016-01-20 11:00:00') 
     .where(courts: {start_time: nil}) 

注意joins在默認情況下是INNER JOIN,所以我們需要明確指出LEFT JOIN