2016-11-30 2 views
0

私はレールが初めてのので、私のアプリケーションにコメント機能を組み込もうとしています。しかし、私は今、迷惑プロジェクトとユーザーのコメント

Couldn't find Project without an ID 

routes.rbを

resources :projects do 
    resources :comments 
    end 

Userモデルを取得しています。

has_many :projects, dependent: :destroy 
    has_many :comments 

プロジェクトモデル。

belong_to :user 
    has_many :comments , dependent: :destroy 

コメントモデル。

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]は送信されませんでした(Parametersハッシュのproject_idはありません)。 ) – lightalloy

+0

あなたはあなたのパラメータに ':project_id'を持っていません –

+0

コメントを作成するために使用される' form'を投稿できますか? –

答えて

1

あなたの書いたものはあなたのform_urlです。しかし、間違いなくproject_idがありません。だから、私はあなたが次のコードを使用することをお勧め:それはroot/projects/2/comments

+0

あなたの答えをありがとう、私は後でそれを行ってあなたに知らせる – Eltorero1992

0

でPOSTリクエストを作成します

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

をすべて以下の投稿をお寄せいただきありがとうございますが、適切なソリューションを

ある
<%= 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 
関連する問題