2017-03-08 112 views
0

我有兩個表,InfoClosure和CityClosure,它有一個外鍵列CityClosure.info_closure_id。活動記錄內部加入

我想獲取InfoClosure.ReferenceDate屬於特定日期範圍的所有CityClosures。

我試圖做到以下幾點:

city_closures = CityClosure.joins(:info_closure).where("info_closures.ReferenceDate >= ? AND info_closures.ReferenceDate <= ?", dateToQueryStart, dateToQueryEnd) 

但我得到的錯誤

StatementInvalid: Mysql2::Error: Unknown column 'info_closures.city_closure_id' in 'on clause': SELECT `city_closures`.* FROM `city_closures` INNER JOIN `info_closures` ON `info_closures`.`city_closure_id` = `city_closures`.`id` WHERE (info_closures.ReferenceDate >= '2017-01-01' AND info_closures.ReferenceDate <= '2017-02-28')> 

我不知道在哪裏活動記錄越來越這info_closures.city_closure_id因爲InfoClosure與CityClosure沒有任何關係,CityClosure具有InfoClosure的外鍵

CityClosure模型我確實有has_many :info_closure

我怎麼能執行這個查詢?爲什麼活動記錄以這種方式連接?

回答

1

這是一個快速的答案,仍然會發布答案,以便其他具有相同問題的人可以找到解決方案。

在InfoClosure模型中,我沒有與CityClosure建立任何連接,並且與InfoClosure的連接錯誤。

所以我添加has_many :city_closure

class InfoClosure < ActiveRecord::Base 
    belongs_to :local 
    has_many :city_closure 
end 

belongs_to :info_closure

class CityClosure < ActiveRecord::Base 
    belongs_to :info_closure 
end 
0

我覺得你在這裏度過了一個錯誤:在CityClosure模式我有一個的has_many

:info_closure

你可以這樣做:

class InfoClosure < ActiveRecord::Base 
    has_many :city_closures, dependent: :destroy 
end 

class CityClosure < ActiveRecord::Base 
    belongs_to :info_closure 
end 

和查詢爲:

city_closures = CityClosure.joins(:info_closure).where("info_closures.ReferenceDate >= ? AND info_closures.ReferenceDate <= ?", dateToQueryStart, dateToQueryEnd)