Rails 5 has_many的动态条件

时间:2016-12-06 17:58:38

标签: ruby postgresql activerecord ruby-on-rails-5 has-many

到处寻找答案。

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

此代码在我的开发环境中生成以下异常。

  

“关联范围'region_location'取决于实例(   范围块采用参数)。预加载实例相关的范围   不受支持。“

看起来Rails 4中有可能出现这种情况,但5(Rails has_many with dynamic conditions)却没有?任何建议将不胜感激。我想过把它变成一个实例方法,但我也使用下面的关联。

has_one :region, :through => :region_location

1 个答案:

答案 0 :(得分: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

这应该为您解决此问题,同时保持相同的功能