Skip to content

Instantly share code, notes, and snippets.

@stevecass
Created April 20, 2016 15:30
Show Gist options
  • Select an option

  • Save stevecass/114c8e498393fceaeb31f21eb0e95982 to your computer and use it in GitHub Desktop.

Select an option

Save stevecass/114c8e498393fceaeb31f21eb0e95982 to your computer and use it in GitHub Desktop.

Revisions

  1. Steven Cassidy created this gist Apr 20, 2016.
    35 changes: 35 additions & 0 deletions poly-associations.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    class Post < ActiveRecord::Base
    has_many :comments, as: :commentable
    end

    class Photo < ActiveRecord::Base
    has_many :comments, as: :commentable
    end

    class Comment < ActiveRecord::Base
    belongs_to :commentable, polymorphic: true
    end

    class CreatePosts < ActiveRecord::Migration
    def change
    create_table :posts do |t|
    t.integer :user_id, index: true
    t.string :title
    t.text :body
    t.string :publication_status
    t.date :published_on
    end

    create_table :photos do |t|
    t.integer :post_id, index: true
    t.string :caption
    end

    create_table :comments do |t|
    t.references :commentable, polymorphic: true, index: true
    t.integer :user_id, index: true
    t.string :body
    end
    end
    end