6

ポリモーフィック モデルで使用delegatehas_manyたりhas_one関連付けたりすることは可能ですか? それはどのように機能しますか?

class Generic < ActiveRecord::Base
    ...

  belongs_to :generable, polymorphic: true

  delegate :file_url, to: :image, allow_nil: true
  delegate :type_cat, to: :cat, allow_nil: true
end

class Image < ActiveRecord::Base
   ...
  has_one :generic, as: generable, dependent: :destroy
end


class Cat < ActiveRecord::Base
   ...
  has_one :generic, as: generable, dependent: :destroy
end
4

2 に答える 2

7

あなたの例から判断するのは難しいので、これがあなたがしようとしていることと正確に一致するかどうかはわかりませんが...

class Generic < ActiveRecord::Base
  ...
  belongs_to :generable, polymorphic: true
  ...
  delegate :common_method, to: :generable, prefix: true
end

class Cat
  def common_method
    ...
  end
end

class Image
  def common_method
    ...
  end
end

次のことを言うことができます。

generic.generable_common_method
于 2013-08-14T17:22:20.940 に答える