Ruby on Rails - How to pass into polymorphic associations?

Is it possible to use delegate with the has_many or has_one in a polymorphic model? How it works?

 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
source share
1 answer

Not sure if this exactly matches what you want to do, as it's hard to say from your example, but ...

 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 

Lets you say the following:

 generic.generable_common_method 
+5
source

Source: https://habr.com/ru/post/1443474/


All Articles