Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- NoMethodError (undefined method `comments' for nil:NilClass):
- app/controllers/comments_controller.rb:9:in `create'
- class CreateComments < ActiveRecord::Migration[5.1]
- def change
- create_table :comments do |t|
- t.references :user, foreign_key: true
- t.text :body, null:false
- t.references :commentable, polymorphic: true, index: true
- t.timestamps
- end
- add_index :comments, [:commentable_id, :commentable_type]
- end
- end
- Rails.application.routes.draw do
- resources :comments, only: [:create]
- resources :votes, only: [:create] do
- delete :reset, on: :collection
- end
- resources :attachments, only: :destroy
- devise_for :users
- resources :questions do
- resources :comments, only: :create, defaults: { commentable: 'questions' }
- resources :answers, shallow: true do
- resources :comments, only: :create, defaults: { commentable: 'answers' }
- patch :set_best, on: :member
- end
- end
- root to: "questions#index"
- mount ActionCable.server => '/cable'
- end
- resources :attachments, only: :destroy
- devise_for :users
- resources :questions do
- resources :comments, only: :create, defaults: { commentable: 'questions' }
- resources :answers, shallow: true do
- resources :comments, only: :create, defaults: { commentable: 'answers' }
- patch :set_best, on: :member
- end
- end
- root to: "questions#index"
- mount ActionCable.server => '/cable'
- end
- comments form partial _comment_form.html.slim:
- h4 Add a comment
- .comment_errors
- = form_for [@commentable, Comment.new], remote: true do |f|
- .form-group
- = f.label :body, 'Comment'
- = f.text_area :body, class: 'form-control'
- p= f.submit 'Create', class: 'btn btn-primary'
- class CommentsController < ApplicationController
- before_action :authenticate_user!
- before_action :load_commentable, only: [:create]
- def create
- @comment = @commentable.comments.create(comment_params.merge(user: current_user))
- end
- private
- def load_commentable
- if params[:comment][:commentable_type] == 'Answer'
- @commentable = Answer.find(params[:comment][:commentable_id])
- gon.answer_id = @commentable.id
- elsif params[:comment][:commentable_type] == 'Question'
- gon.answer_id = @commentable.id
- @commentable = Question.find(params[:comment][:commentable_id])
- end
- end
- def comment_params
- params.require(:comment).permit(:body, :commentable_type, :commentable_id )
- end
- end
- h3 Comments
- .question_comments id="comments_section_question_#{@question.id}"
- - if user_signed_in?
- .row
- = render 'comments/comment_form', commentable: @question
Add Comment
Please, Sign In to add comment