没有ID无法找到评论

时间:2014-01-21 04:13:18

标签: ruby-on-rails

我有2个模型:评论和问题(问题属于评论)。在尝试创建新问题时,我会收到此错误,突出显示控制器的第一行。它一直工作到最近,所以我不知道什么导致错误。

Couldn't find Comment without an ID

控制器如下所示:

def create
@comment = Comment.find(params[:comment_id])
@question = @comment.questions.new(question_params)
end

路线如下:

resources :comments do
  resources :questions 
end

发布后,重定向到' / questions'即使它指定了不同的路径。

问题形成:

<%= simple_form_for [@comment, Question.new] do |f| %>
<%= f.input :body, as: :text %>
<%= f.submit "Ask", :id => "button", class: "button5" %>
<% end %>

参数:

utf8"=>"✓", "authenticity_token"=>"NJdlwZujnOpNfg6XZGyqFIPhIPSQ47GDWrUVJGkapR8=", "question"=>{"user_id"=>"1", "body"=>"hi"}, "commit"=>"Ask"}

PARAMS:

params.require(:question).permit(:body, :title, :comment_id, :user_id, :image, :image_remote_url, :caption)

3 个答案:

答案 0 :(得分:0)

看起来params [:comment_id]是零。

答案 1 :(得分:0)

为params添加一个空白支票,或者您可以find_by_id进行评论,以便它返回nil,并且只有在您收到评论时才能创建问题

@comment = Comment.find_by_id(params[:comment_id])
@question = @comment.question.new(question_params) if @comment.present?

答案 2 :(得分:0)

你应该尝试这一行来找到你的评论:

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

我相信您的问题是您的路由是将id作为:id参数提供。

尝试跑步:

rake routes

并查看路线以验证它返回给您的是什么样的参数。你应该看到:id。