多态注释:无法传递类型和 id (NoMethodError for nil:NilClass)



我正在尝试为QuestionAnswer创建多态注释,但是当我点击"创建注释"表单上的"创建"按钮时,commentable_typecommentable_id永远不会通过。我可以通过Rails Console成功创建新评论,但不能通过表格(目前我正在测试问题的评论)。我在load_commentable或controller的create中遇到错误,例如:

NoMethodError (undefined method `comments' for nil:NilClass):
app/controllers/comments_controller.rb:9:in `create'

似乎@commentablenil(因为它没有commentable_typecommentable_id参数?)。我错过了什么?

评论迁移:

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

routes.rb:

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

评论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'

comment_controller:

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

错误日志:

app/controllers/comments_controller.rb:7:in `create'
Started POST "/comments" for 10.0.2.2 at 2017-11-20 20:54:42 +0000
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by CommentsController#create as JS
  Parameters: {"utf8"=>"✓", "comment"=>{"body"=>"kkkk"}, "commit"=>"Create"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 41], ["LIMIT", 1]]
Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.4ms)

NoMethodError (undefined method `comments' for nil:NilClass):
app/controllers/comments_controller.rb:7:in `create'

我认为您的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'
    = hidden_field_tag 'commentable[id]', @commentable.id
    = hidden_field_tag 'commentable[type]', @commentable.class.name
  p= f.submit 'Create', class: 'btn btn-primary'

应该为您提供类似的参数:

Parameters: {"utf8"=>"✓", "comment"=>{"body"=>"kkkk"}, "commentable"=>{"id"=>"1", "type"=>"Question"}, commit"=>"Create"}

然后,您将load_commentable更改为:

def load_commentable
  @commentable = commentable_params[:type].constantize.find_by(id: commentable_params[:id])
  gon.answer_id = @commentable.id
end

(顺便说一句,gon.answer_id,当您有一个问题时似乎很奇怪。但是,我不知道...)

自然需要类似的东西:

def commentable_params
  param.require(:commentable).permit(:id, :type)
end

最新更新