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

时间:2017-11-20 21:18:30

标签: ruby-on-rails polymorphic-associations

我尝试为QuestionAnswer创建多态评论,但是当我点击"创建&时,commentable_typecommentable_id永远不会通过#34;按钮"创建评论"形成。我可以通过rails控制台成功创建一个新评论,但不是通过表单(目前我正在测试评论的问题)。我在comments_controller的load_commentablecreate收到错误,例如:

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

评论表单部分_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'

comments_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'

1 个答案:

答案 0 :(得分:1)

我认为你的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

(BTW,gon.answer_id,如果你有一个问题似乎很奇怪。但是,我不知道...)

当然,这需要类似的东西:

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