1

我需要更改活动记录查询中返回的每个结果的类。每当运行任何查询并返回结果时,我都希望发生这种情况。不幸的是,我不能使用 STI 来实现这一点。例如:

class Foo < ActiveRecord::Base

   after_find :becomes_a_subclass

   def becomes_a_subclass
      becomes [Bar, Baz, Raz].sample
   end

end

class Bar < Foo ; end
class Baz < Foo ; end
class Raz < Foo ; end

我希望以下内容返回给定的结果:

=> Foo.all
[#<Bar id: 1>, #<Baz id: 2>, #<Bar id: 3>, #<Raz id: 4>]
4

1 回答 1

1

您需要discriminate_class_for_record(record)Foo. 这应该返回记录的子类。示例实现:

class Foo < ActiveRecord::Base

  def self.discriminate_class_for_record(record)
    if record['foobar']
      [Bar, Baz, Raz].sample
    else
      super
    end
  end

end

class Bar < Foo ; end
class Baz < Foo ; end
class Raz < Foo ; end
于 2017-03-22T15:35:36.570 回答