Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - How to delegate to polymorphic associations?

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
like image 348
Chim Kan Avatar asked Nov 01 '12 15:11

Chim Kan


People also ask

How is polymorphic association set up in Rails?

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.

What is polymorphic association in Ruby on Rails?

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.

How does delegate work in Rails?

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.

What is polymorphic Ruby?

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.


1 Answers

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
like image 119
Joseph Siefers Avatar answered Oct 17 '22 12:10

Joseph Siefers