鍍金池/ 問(wèn)答/網(wǎng)絡(luò)安全/ rails多態(tài)怎么在頁(yè)面中調(diào)用?

rails多態(tài)怎么在頁(yè)面中調(diào)用?

rails多態(tài)問(wèn)題:

我現(xiàn)在有問(wèn)題,文章,評(píng)論三個(gè)模型,一個(gè)問(wèn)題對(duì)應(yīng)多個(gè)評(píng)論,一篇文章對(duì)應(yīng)多個(gè)評(píng)論,現(xiàn)在怎么在問(wèn)題下提交評(píng)論?。

我的models如下:

#comment.rb
class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

#question.rb
class Question < ActiveRecord::Base
   has_many :comments, :as => :commentable, :dependent => :destroy
 end

我的question的show.html.erb評(píng)論代碼如下:

<% @comment = @question.comments.build  %>
<%= form_for([@comment.commentable,@comment]) do |f| %>
    <%= f.text_area :content,class: "editormd-markdown-textarea" %>
    <%= f.submit "提交", class: "btn btn-primary pull-right" %>
<% end %>

我的question_controller.rb部分如下:

def create
   Question.find(params[:question_id]).comments.build
end

我的roots.rb部分代碼如下

resources :questions do
    resources :comments
  end

但是我得了這個(gè)錯(cuò)誤,請(qǐng)問(wèn)我該怎么做呢?哪里出錯(cuò)了呢?非常感謝。

Routing Error
uninitialized constant CommentsController
回答
編輯回答
來(lái)守候

主要問(wèn)題在于這語(yǔ)句:

<%= form_for([@comment.commentable,@comment]) do |f| %>

這句實(shí)質(zhì)就是<%= form_for([@question, @comment]) do |f| %>
url: "/questions/2/comments" (post請(qǐng)求)
也就是說(shuō)你是給這個(gè)question添加評(píng)論,需要comments控制器,并定義create方法
但是你沒(méi)有定義

2017年11月4日 09:54