2016-12-06 43 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