Skip to content

Instantly share code, notes, and snippets.

@beneggett
Last active July 17, 2022 05:06
Show Gist options
  • Save beneggett/9201125 to your computer and use it in GitHub Desktop.
Save beneggett/9201125 to your computer and use it in GitHub Desktop.
Polymorphic Associations

Creating polymorphic associations

Create Tagging feature:

Create keywords to reference our media

Tag: name: (keyword)

Steps: 1 of 3

  1. Generate a model per usual, only reference a "polymorphic association name" (that you'll invent) as the reference model
rails g model Tag name:string taggable:references

Steps: 2 of 3

  1. Tell Rails you are using polymorphic associations in your models:

• In the polymorphic model itself, set polymorphic: true on the belongs_to :taggable

class Tag < ActiveRecord::Base
  belongs_to :taggable, polymorphic: true
  attr_accessible :name
end

• In our migration, we'll also want to set polymorphic: true

class CreateTags < ActiveRecord::Migration
  def change
    create_table :tags do |t|
      t.string :name
      t.references :taggable, polymorphic: true
      t.timestamps
    end
    add_index :tags, :taggable_id
  end
end

Steps: 3 of 3

  1. When we want to use polymorphic models in other models, we simply create the association
class Post < ActiveRecord::Base
  # ...
  has_many :tags, as: :taggable
  # ...
end

Assignment

• Create tags within your app • Create projects scaffold • Create Pictures/Images polymorphic association and use it with your projects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment