Skip to content

Instantly share code, notes, and snippets.

@tmaximini
Created November 2, 2011 17:23
Show Gist options
  • Save tmaximini/1334286 to your computer and use it in GitHub Desktop.
Save tmaximini/1334286 to your computer and use it in GitHub Desktop.
polymorphic association
# models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, :polymorphic => true
end
# models/post.rb
class Post < ActiveRecord::Base
belongs_to :post_category
belongs_to :user
has_many :comments, :as => :commentable
end
# models/user.rb
class User < ActiveRecord::Base
has_many :comments
has_many :posts
end
# controllers/comments_controller.rb
class CommentsController < ApplicationController
before_filter :authenticate_user!
def index
@commentable = find_commentable
@comments = @commentable.comments
end
def show
@comment = Comment.find(params[:id])
end
def new
@comment = Comment.new
end
# GET /comments/1/edit
def edit
@comment = Comment.find(params[:id])
end
# POST /comments
# POST /comments.json
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
if @comment.save
redirect_to @comment, :notice => 'Comment was successfully created.'
redirect_to :id => nil
else
render :action => "new"
end
end
def update
@comment = Comment.find(params[:id])
if @comment.update_attributes(params[:comment])
redirect_to @comment, :notice => 'Comment was successfully updated.'
else
render :action => 'edit'
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to comments_url, :message => 'Comment deleted.'
end
# find commentable (parent) item
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
# view partial (haml)
= form_for [@commentable, Comment.new], :remote => true do |f|
#new_comment.add_comment
= f.hidden_field :user_id, :value => current_user.id
= f.text_field :content, :size => 55, :value => 'leave a comment...', :onfocus => 'this.select()', :class => 'comment_form'
= f.submit "send"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment