Created
January 19, 2011 06:02
-
-
Save harfangk/785764 to your computer and use it in GitHub Desktop.
polymorphic
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 Comment < ActiveRecord::Base | |
belongs_to :commentable, :polymorphic => true | |
end | |
class Article < ActiveRecord::Base | |
has_many :comments, :as => :commentable | |
end | |
class Photo < ActiveRecord::Base | |
has_many :comments, :as => :commentable | |
#... | |
end | |
class Event < ActiveRecord::Base | |
has_many :comments, :as => :commentable | |
end | |
# comments_controller | |
def index | |
@commentable = find_commentable | |
@comments = @commentable.comments | |
end | |
def create | |
@commentable = find_commentable | |
@comment = @commentable.comments.build(params[:comment]) | |
if @comment.save | |
flash[:notice] = "Successfully created comment." | |
redirect_to :id => nil | |
else | |
render :action => 'new' | |
end | |
end | |
private | |
def find_commentable | |
params.each do |name, value| | |
if name =~ /(.+)_id$/ | |
return $1.classify.constantize.find(value) | |
end | |
end | |
nil | |
end | |
# routes.rb | |
map.resources :articles, :has_many => :comments | |
map.resources :photos, :has_many => :comments | |
map.resources :events, :has_many => :comments | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment