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 c17c23c..ec6e4ad 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 75883be..4de28bf 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'