渴望加载兄弟记录而不包括自我

时间:2017-11-13 18:26:56

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

对于序列化,我想包含一个共享共同外键的兄弟记录数组。我目前有以下内容:

class Foo < ActiveRecord::Base
  has_many :other_instances,
           source: :foo,
           class_name: 'Foo',
           foreign_key: 'event_id',
           primary_key: 'event_id'

在include中使用时,会产生以下查询:

  Foo Load (0.2ms)  SELECT  "foo".* FROM "foo" WHERE "foo"."id" = $1 LIMIT 1  [["id", 21138]]
  Foo Load (0.4ms)  SELECT "foo".* FROM "foo" WHERE "foo"."event_id" IN (11451)

这主要有用,但问题在于Foo.other_instances包含了自己。有没有办法在rails中排除那个额外的记录?预期的includes看起来像这样:

  Foo Load (0.4ms)  SELECT "foo".* FROM "foo" WHERE "foo"."event_id" IN (11451) AND "foo"."id" NOT IN (21138)

更新

尝试使条件实例依赖于@spikermann&#39; s导致以下结果:

代码:

has_many :other_instances,
         source: :foo,
         class_name: 'Foo',
         foreign_key: 'event_id',
         primary_key: 'event_id', 
         ->(foo) { where.not(id: foo.id) }

跟:

Foo.includes(:other_instances).find(21138)

结果:

DEPRECATION WARNING: The association scope 'other_instances' is instance dependent (the scope block takes an argument). Preloading happens before the individual instances are created. This means that there is no instance being passed to the association scope. This will most likely result in broken or incorrect behavior. Joining, Preloading and eager loading of these associations is deprecated and will be removed in the future. (called from check_preloadable! at /home/jordan/prog/knotweed/vendor/bundle/gems/activerecord-4.2.7.1/lib/active_record/reflection.rb:362)
NoMethodError: undefined method `id' for nil:NilClass

1 个答案:

答案 0 :(得分:1)

添加范围怎么样:

has_many :other_instances,
         source: :foo,
         class_name: 'Foo',
         foreign_key: 'event_id',
         primary_key: 'event_id', 
         ->(foo) { where.not(id: foo.id) }