1
votes

Im not sure i understand rails polymorphic. In Java you can create Objects from the same Objecttype: http://www.fh-kl.de/~guenter.biehl/lehrgebiete/java2/j2-08-Dateien/abb.8.10.jpg

 Person trainer = new Trainer()
 Person sportler = new Trainer()

In Rails http://guides.rubyonrails.org/association_basics.html#polymorphic-associations:

In this example: picture can be from an employee or from a product, sounds strange because this is not realy the same type.

Do i understand the real purpose: to save objects in the same container an array of person or image?

In my rails project: I have several person: sportsmen, trainer and guest. They are sons of person (inheritance). I think i meet the inheritance reason.

There is another class named exercise.

Sportsmen and trainer can create exercises.

So i want to use polymorphic. Exercises can be from trainer or sportsmen. Like in the example of the rails page, images can be from employee or a product.

Do i meet the best practise?

How do i implement a has_many :through with polymorphy? It is not possible to use a habtm assoziation with polymorphic. You have to define a additional class, but how exactly?

2

2 Answers

0
votes
0
votes

Just to make it clear, you should use polymorphic associations when you have a model that may belong to many different models on a single association.

Suppose, you want to be able to write comments for users and stories. You want both models to be commendable. Here's how this could be declared:

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :comment, as: :commentable
end

class Product < ApplicationRecord
  has_many :comment, as: :commentable
end

To declare the polymorphic interface (commendable) you need to declare both a foreign key column and a type column in the model.

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :body
      t.integer :commentable_id
      t.string :commentable_type
      t.timestamps
    end

    add_index :comments, :commentable_id
  end
end

You can check more details about associations here.