【问题标题】:Eager loading relation when relation is defined by finder_sql - ignores finder_sql and build default has_many query当 finder_sql 定义关系时急切加载关系 - 忽略 finder_sql 并构建默认的 has_many 查询
【发布时间】:2012-10-16 09:29:57
【问题描述】:

有一个类叫做Location。我想在单个查询中预加载所有直接子级。

Location类关系中定义如下:

has_many :children,
  class_name: self,
  finder_sql: ->(query) {
      self.class.where(%Q{"locations"."ancestry" like '%#{id}'}).to_sql
  },
  counter_sql: ->(query) {
    self.class.where(%Q{"locations"."ancestry" like '%#{id}'}).count.to_sql
  }


Location.first.children
  Location Load (0.4ms)  SELECT "locations".* FROM "locations" LIMIT 1
  Location Load (0.3ms)  SELECT "locations".* FROM "locations" WHERE ("locations"."ancestry" like '%1')
  => [#<Location id: 2, code: nil, name: "Niger 1349875728.873964", alternative_name: nil, ancestry: "1", coordinates: nil, ancestry_depth: 1>, (...)]

但是当我想优化它并分两批加载所有内容时:

Location.includes(:children).where(id: [5, 100]).all
  Location Load (0.4ms)  SELECT "locations".* FROM "locations" WHERE "locations"."id" IN (5, 100)
  Location Load (0.2ms)  SELECT "locations".* FROM "locations" WHERE "locations"."location_id" IN ('5')
  ActiveRecord::StatementInvalid: PG::Error: ERROR:  column locations.location_id does not exist
  LINE 1: SELECT "locations".* FROM "locations"  WHERE "locations"."lo...
                                                 ^
  : SELECT "locations".* FROM "locations"  WHERE "locations"."location_id" IN ('5')
  from /xxx/.rvm/gems/ruby-1.9.3-p194@gsp/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1158:in `async_exec'

这是 Rails 中的错误,还是我应该以不同的方式定义它?

我也在尝试覆盖关系上的 find_in_collection,但它没有影响。

【问题讨论】:

    标签: activerecord ruby-on-rails-3.2 has-many eager-loading


    【解决方案1】:

    是的,您在这里与 Rails 的战斗有点过火了。在 has_many 上使用条件参数:

    has_many :children, class_name: self, conditions: [%Q{"locations"."ancestry" like '%#{id}'}]
    

    还只是想知道 like 的用法吗?为什么不测试 =?

    has_many :children, class_name: self, foreign_key: :ancestry
    

    此外,如果你走那条路,那在风格上应该有一个 _id:

    has_many :children, class_name: self, foreign_key: :ancester_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多