简体   繁体   中英

Couldn't find Post without an ID even though request parameters says I do

To me this is a strange one.

I have 2 models (with User), I have post and I have comment. What I am trying to do is to have the form_for comments in the post#show view.

However for some reason when I try to create a comment I get Couldn't find Post without an ID. When I look at the request parameters though I see:

{"utf8"=>"✓", "authenticity_token"=>"7bAXF66sghTKAF7b61gu08hElC+O1nR6RoT92tqQGOI=",     "comment"=>{"content"=>"ok"}, "commit"=>"Add comment", "action"=>"create", "controller"=>"comments", "post_id"=>"23"}

which clearly shows that it does in-fact get the post_id and that it is in this case the id of 23.

After countless hours I thought that I'd see if you guys have a solution.

My comments_controller.rb :

class CommentsController < ApplicationController
 before_action :load_post

 def create
  @comment = @post.comments.build(params[:content])
  @comment.user = current_user
  if @comment.save
   @comment.create_activity :create, owner: current_user
   redirect_to root_url, notice: "Comment was created."
  else
   render :new
 end

 def load_post
  @post = Post.find(params[:id])
 end
end

My posts_controller.rb

  def show
   @post = Post.find(params[:id])
   @comment = Comment.new
  end

the partial for the forms comments/_form.rb

<%= form_for [@post, @comment] do |f| %>
 <%= f.text_area :content %>
 <%= f.submit "Add comment" %>
<% end %>

My routes.rb

  resources :posts do 
   resources :comments 
  end

my posts/show.html.erb

<%= render @post %>

 <h3>New comment</h3>

 <%= render 'comments/form' %>

my posts/_post.html.erb

<h2><%= @post.title %></h2>
<p><%= @post.content %></p>
<em>written by <%= @post.user.fullname %></em>

You are receiving "post_id" not as "id"

You can make load_post action as private for security concerns

private

 def load_post
  @post = Post.find(params[:post_id])
 end

Access the content like

def create
 @comment = @post.comments.build(params[:comment][:content]) 
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM