我刚刚开始使用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
评论模型。
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 :(得分:1)
我不知道你的 form_url 上写了什么。但是,肯定它缺少project_id
。所以,我建议你使用以下代码:
<%= form_for [@project, @comment] do |f| %>
它会在root/projects/2/comments
答案 1 :(得分:0)
感谢所有您的帖子,以下是正确的解决方案
<%= 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