-
-
Save nakajima/61adb61c97593a26a701 to your computer and use it in GitHub Desktop.
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
# 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