2016-11-30 51 views
0

我剛剛接觸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'來創建評論 –

回答

1

我不知道你的form_url上寫了什麼。但是,它絕對是缺少project_id。所以,我建議你使用下面的代碼:

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

它會在root/projects/2/comments

+0

感謝您的回答我將在稍後介紹它並讓您知道 – Eltorero1992

0

感謝所有爲您的帖子下方創建一個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