Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created July 10, 2009 21:25
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 nakajima/61adb61c97593a26a701 to your computer and use it in GitHub Desktop.
Save nakajima/61adb61c97593a26a701 to your computer and use it in GitHub Desktop.
# app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :story
belongs_to :user
end
# app/models/user.rb
class User < ActiveRecord::Base
has_many :comments
end
# app/models/story.rb
class Story < ActiveRecord::Base
belongs_to :user
has_many :comments
end
# config/routes.rb
map.resources :stories do |story|
story.resources :comments
end
# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
before_filter :login_required, :only => [ :create, :destroy ]
def create
@story = Story.find(params[:story_id])
@comment = @story.comments.build(params[:comment].merge(:user => current))
if @comment.save
flash[:notice] = 'Comment was successfully created.'
redirect_to(@story)
else
flash[:notice] = "Error creating comment: #{@comment.errors}"
redirect_to(@story)
end
end
def destroy
# Using the current_user.stories association proxy ensures that
# users will only be able delete comments on their own stories
@story = current_user.stories.find(params[:story_id])
@comment = @story.comments.find(params[:id])
@comment.destroy
redirect_to(@story)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment