一直在到处寻找这个问题的答案。
has_one :region_location, ->(location) { where("region_locations.site_id = ?", location.current_site.id) if location.current_site }
此代码在我的开发环境中生成以下异常。
"The association scope 'region_location' is instance dependent (the scope block takes an argument). Preloading instance dependent scopes is not supported."
这似乎在 Rails 4 中可行,但在 5 中不行(Rails has_many with dynamic conditions)?任何建议将不胜感激。我考虑过将其改为实例方法,但我也使用了下面的关联。
has_one :region, :through => :region_location
最佳答案
您可以将其设为实例方法。例如
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
这应该可以为您解决这个问题,同时保持相同的功能
关于ruby - has_many 的 Rails 5 动态条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41001861/