Is it possible to use delegate
with has_many
or has_one
association in a polymorphic model? How does that work?
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
The basic structure of a polymorphic association (PA)sets up 2 columns in the comment table. (This is different from a typical one-to-many association, where we'd only need one column that references the id's of the model it belongs to). For a PA, the first column we need to create is for the selected model.
Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.
On the Profile side we use the delegate method to pass any class methods to the User model that we want access from our User model inside our Profile model. The delegate method allows you to optionally pass allow_nil and a prefix as well. Ultimately this allows us to query for data in custom ways.
Polymorphism is a key component of object-oriented programming. To simplify things, it is based on the fact that objects of different classes have access to the same interface, which means that we can expect from each of them the same functionality but not necessarily implemented in the same way.
Not sure if this exactly matches what you're looking to do, as it's tough to tell 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
Allows you to say the following:
generic.generable_common_method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With