【问题标题】:Rails 5 Dynamic Conditions for has_manyhas_many的Rails 5动态条件
【发布时间】:2017-04-21 11:24:59
【问题描述】:

一直在到处寻找这个问题的答案。

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

【问题讨论】:

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


    【解决方案1】:

    你可以把它变成一个实例方法。例如

    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
    

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

    【讨论】:

    • 谢谢。这似乎有效。不过肯定会减慢速度,因为使用 sunspot solr 我不能再使用 :includes 来定义以这种方式定义的关系了。
    • @BenScheib 嗯,这有点难。可能需要深入研究 Rails 源代码才能找到解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2014-04-24
    相关资源
    最近更新 更多