2016-12-06 46 views
3

一直在尋找答案。Rails 5動態條件has_many

has_one :region_location, ->(location) { where("region_locations.site_id = ?", location.current_site.id) if location.current_site } 

此代碼在我的開發環境中生成以下異常。

「的關聯範圍‘region_location’是實例依賴性的(在 範圍塊需要一個參數)。預壓實例依賴範圍不支持 」。

看來喜歡的事,在軌道4,5是可能的,但不是在5(Rails has_many with dynamic conditions)?任何建議將不勝感激。我想讓它成爲實例方法,但我也使用下面的關聯。

has_one :region, :through => :region_location 

回答

0

您可以改爲實例方法。例如

def region_location 
    RegionLocation.find_by_site_id(self.current_site.id) if self.current_site 
end 

和第二部分可能只是

delegate :region, to: :region_location, allow_nil: true 

這應該解決這個問題,你同時保持相同的功能

+0

感謝。這似乎工作。肯定會減慢速度,但因爲太陽黑子solr我不能做:包括用這種方式定義的關係。 –

+0

@BenScheib嗯,這有點困難。可能需要挖掘rails源以找到解決方案 – engineersmnky