对项目和用户的评论

问题描述:

我刚刚接触rails,我正在尝试在我的应用中添加评论功能。但是我得到了现在讨厌对项目和用户的评论

Couldn't find Project without an ID 

的routes.rb

resources :projects do 
    resources :comments 
    end 

用户模型。

has_many :projects, dependent: :destroy 
    has_many :comments 

项目模型。

belong_to :user 
    has_many :comments , dependent: :destroy 

评论model。

belongs_to :user 
    belongs_to :project 

评论控制器。

class CommentsController < ApplicationController 
    before_action :logged_in_user, only: [:create, :destroy] 

def create 
    @project = Project.find(params[:project_id]) 
    @comment = @project.comments.build(comment_params) 
    @comment.user_id = current_user.id 
     if @comment.save 
     flash[:success] = "Comment created!" 
     redirect_to @project 
    else 
     flash.now[:danger] = "Sorry! your comment was not created" 
    end 
    end 


def destroy 
    end 

    private 

    def comment_params 
    params.require(:comment).permit(:body) 
end 

end 

结果

Parameters: {"utf8"=>"✓", "authenticity_token"=>"+/UjIRKAjE+DAATW6eV48xjX+6WW6a/y7Q8DS+nLeCnM8nzwpdzW1FuGXtXVpCGFS0vPivvMi7jvus9IQcjLjA==", "comment"=>{"body"=>""}, "commit"=>"Comment"} 
    User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]] 
Completed 404 Not Found in 24ms (ActiveRecord: 1.3ms) 



ActiveRecord::RecordNotFound (Couldn't find Project without an ID): 

----更新1 -------

<%= form_for(@comment) do |f| %> 
    <%= render 'shared/error_messages', object: f.object %> 
    <div class="field"> 
    <%= f.text_area :body, placeholder: "Write here" %> 
    </div> 
    <%= f.submit "comment", class: "btn btn-primary" %> 
<% end %> 

任何想法?

+0

正如你在日志中看到的params [:project_id]没有发送(参数hash中没有project_id ) – lightalloy

+0

您的参数中没有':project_id' –

+0

您可以发布'form'来创建评论 –

我不知道你的form_url上写了什么。但是,它绝对是缺少project_id。所以,我建议你使用下面的代码:

<%= form_for [@project, @comment] do |f| %> 

它会在root/projects/2/comments

+0

感谢您的回答我将在稍后介绍它并让您知道 – Eltorero1992

感谢所有为您的帖子下方创建一个POST请求是正确的解决方案

<%= form_for ([@project , @comment]) do |f| %> 
    <%= render 'shared/error_messages', object: f.object %> 
    <div class="field"> 
    <%= f.text_area :body, placeholder: "Compose new micropost..." %> 
    </div> 
    <%= f.submit "Comment", class: "btn btn-primary" %> 
<% end %> 

PARAMS

def comment_params 
    params.require(:comment).permit(:body,:project_id,:user_id) 
end