-
-
Save puneetpandey/2810beadd5b888d3f80a to your computer and use it in GitHub Desktop.
Rails Polymorphic associations explained
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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