From 9d98e545bbecbecb33104d784562e8d8ed157d57 Mon Sep 17 00:00:00 2001 From: Yuka Kato Date: Fri, 2 Sep 2016 17:14:52 +0900 Subject: [PATCH] [ci skip][WIP]Create comments --- app/controllers/comments_controller.rb | 22 ++++++++++++++++++++++ app/controllers/posts_controller.rb | 1 + app/views/posts/show.html.slim | 4 ++++ config/routes.rb | 2 +- 4 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 app/controllers/comments_controller.rb diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb new file mode 100644 index 0000000..96d241e --- /dev/null +++ b/app/controllers/comments_controller.rb @@ -0,0 +1,22 @@ +class CommentsController < ApplicationController + def index + @comments = Comment.all + end + + def create + post = Post.find(params[:post_id]) + @comment = post.comments.build(comment_params) + + if @comment.save + redirect_to post, notice: 'Comment has been successfully created.' + else + redirect_to post, alert: 'Hoge!' + end + end + + private + + def comment_params + params.require(:comment).permit(:body).merge(commented_by: current_user) + end +end diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index 2f6c7f6..63b8e36 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -6,6 +6,7 @@ def index end def show + @comment = @post.comments.new @comments = @post.comments end diff --git a/app/views/posts/show.html.slim b/app/views/posts/show.html.slim index 6a067f2..5581e6e 100644 --- a/app/views/posts/show.html.slim +++ b/app/views/posts/show.html.slim @@ -15,6 +15,10 @@ .author__created-at.grey-text.text-darken-1 = @post.created_at + = form_for @comment, url: post_comments_path(@post) do |f| + = f.text_field :body + = f.submit + - @comments.each do |comment| .comment .author diff --git a/config/routes.rb b/config/routes.rb index e2acbbc..1ed2c9d 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -2,7 +2,7 @@ root to: "posts#index" resources :users, only: %i( index show ) resources :posts do - resources :comments, only: %i( index ) + resources :comments, only: %i( index new create ) end get "login", to: "sessions#new"