Rails 4 Param Not Found Show Action

时间:2015-07-02 15:18:17

标签: ruby-on-rails

我正在创建一个博客平台,我正致力于让我的评论功能发挥作用。它工作但突然停止并开始抛出此错误。我在我的文章显示页面中有一个评论表单.ConjectController :: ParameterMissing在CommentsController #create中 未找到Param:评论

以下是代码:

comments_controller.rb

class CommentsController < ApplicationController

def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    flash[:notice] = "Your comment has been saved!"
    redirect_to article_path(@article)
end

def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy

    redirect_to(@comment.post)
end

private
def comment_params
    params.require(:comment).permit(:commenter, :comment)
end
end

文章show.html.erb

以下是我的评论表

<div class="container com_form">
<h4>Add a Comment</h4>
<%= form_for([@article, @article.comments.build]) do |f| %>
  <b><%= f.label :commenter %></b>
  <p><%= f.text_field :commenter %></p>

  <b><%= f.label :comment %></b>
  <p><%= f.text_area :comment %></p>

<p>
<%= f.submit %>
</p>
<% end %>
</div>

应用程序跟踪

app/controllers/comments_controller.rb:19:in `comment_params'
app/controllers/comments_controller.rb:5:in `create

我不确定为什么突然间它会填充这个错误。任何帮助是极大的赞赏。

更新

的routes.rb

devise_for :users, controllers: {
    sessions: 'users/sessions'
  }

resources :users

resources :articles do
  resources :comments
end

root 'pages#index'
get 'users/sign_in' => 'users/sessions#create'
post 'users/sign_in' => 'users/sessions#create'
post '/articles/:article_id/' => 'comments#create'
post 'articles/new' => 'articles#create'
get 'articles/:id' => 'articles#show'
patch 'articles/:id' => 'articles#update'
get 'atricles/:id/edit' => 'articles#edit'
delete '/articles/:id' => 'articles#destroy'
get 'users/:username' => 'users#show'

链接到错误屏幕截图

Error Screenshot

链接到GitHub上的回购

Blog Repo

2 个答案:

答案 0 :(得分:0)

如您所见,发送的参数中没有评论信息。 我不确定,但在文章的节目视图中尝试将@ article.comments.build更改为Comment.new(author_id:@ article.id)。

答案 1 :(得分:0)

在第<%= form_for([@article, @article.comments.build]) do |f| %>行中,尝试将其更改为Comment.new

您正在处理控制器中的Active Record关联:

@comment = @article.comments.create(comment_params)

更新

将表单更改为以下内容:

<%= form_for([@article, Comment.new]) do |f| %>
  <b><%= f.label :commenter %></b>
  <p><%= f.text_field :commenter %></p>

  <b><%= f.label :comment %></b>
  <p><%= f.text_area :comment %></p>

<p>
<%= f.submit %>
</p>
  

或者,由于您在show controller操作中定义@comment = Comment.new,因此可以使用:

form_for([@article, @comment])