Skip to content

Instantly share code, notes, and snippets.

@puneetpandey
Last active December 18, 2015 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save puneetpandey/2810beadd5b888d3f80a to your computer and use it in GitHub Desktop.
Save puneetpandey/2810beadd5b888d3f80a to your computer and use it in GitHub Desktop.
Rails Polymorphic associations explained
class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :comments, :as => :commendable
end
class Event < ActiveRecord::Base
attr_accessible :name, :organizer, :place
has_many :comments, :as => :commendable
end
class Comment < ActiveRecord::Base
attr_accessible :comment
belongs_to :commendable, :polymorphic => true
end
# Migration: create_comments.rb
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :comment
t.references :commendable, :polymorphic => true
t.timestamps
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment