ruby - has_many 的 Rails 5 动态条件

标签 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 }

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

"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/

相关文章:

ruby - 为什么在表单中使用 POST 方法会返回错误 404?

ruby-on-rails - 如何克服 Excel CSV 编码噩梦 : "\xEF" from ASCII-8BIT to UTF-8"using Ruby on Rails

ruby-on-rails - 为 Grape API 添加路径/自动加载路径不起作用

Postgresql:在给定子字符串之前提取数字

ruby-on-rails - 如何在 Rails 事件记录查询中使用包含内的连接?

ruby - 使用 step 遍历数组

mysql - 从所有数据库的查询结果中获取顶部记录

sql - 多个 ID 的公差范围内的最接近值

ruby-on-rails - has_one 是否没有提供 `create_child` 方法?

ruby-on-rails - Controller 中的 Rails 异常执行查询实例变量?