0

次の例を考えてみましょう。

class Ball < ActiveRecord::Base
  def is_ball?
    true
  end
end

class BlueBall < Ball
  def color
    :blue
  end
end

class RedBall < Ball
  def color
    :red
  end
end

Ball.find(id)のインスタンスをBlueBall返すことは可能ですか?

とインスタンスでBall.where(owner: some_user).to_a配列を取得できますか?BlueBallRedBall


それ以外の列を使用して、STI を明示的に設定する方法を探していtypeます。

4

1 に答える 1

1

Redこれは、クラスの名前をandBlueの代わりにRedBallandに変更できる場合に機能します。BlueBall

def Ball < ActiveRecord::Base

  self.inheritance_column = :color

  def ball?
    is_a?(Ball)
  end

end

def Red < Ball
  # Red#color would return 'Red'
end

def Blue < Ball
  # Blue#color would return 'Red'
end
于 2012-11-15T04:45:59.107 に答える