私はレールが初めてのので、私のアプリケーションにコメント機能を組み込もうとしています。しかし、私は今、迷惑プロジェクトとユーザーのコメント
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 %>
任意のアイデアを更新?
ログに表示されているように、params [:project_id]は送信されませんでした(Parametersハッシュのproject_idはありません)。 ) – lightalloy
あなたはあなたのパラメータに ':project_id'を持っていません –
コメントを作成するために使用される' form'を投稿できますか? –