H.Akca
H.Akca

Reputation: 53

Rails: Not routes match

I get this error with my code

enter image description here

i get this error with this line into my show.html.haml for the comment

= link_to comment.user_name, user_path(comment.user_id)

in my create action i have this

def create
  @comment = @post.comments.new(comment_params)
  @comment.user_name = current_user.nickname
  @comment.user_id = current_user.id
  if @comment.save!
    redirect_to @post
  else
    flash.now[:danger] = "error"
  end
end

thank you for your help

Upvotes: 0

Views: 56

Answers (2)

Sovalina
Sovalina

Reputation: 5609

According to your post view, you build an empty comment for the current post:

= render 'comments/form', comment: @post.comments.build

That's why, when you iterate on @post.comments.each, @post has one unsaved built comment without user.

You can fix this by adding a condition like:

- @post.comments.each do |comment|
  - unless comment.new_record?
    .div
      %hr
       = link_to comment.user_name, user_path(comment.user_id)
       ...

Or you can add in your PostsController:

def show
  @comment = Comment.new
end

and change = render 'comments/form', comment: @post.comments.build to = render 'comments/form', comment: @comment
This way @post.comments is empty and you can iterate on it without missing id error.

Upvotes: 2

MATTALUI
MATTALUI

Reputation: 1

The error being displayed missing required keys: [:id] implies that the arguments to user_path are not being passed in as we might be expecting them to. comment.user_id might be nil or you might have to specify explicitly = link_to comment.user_name, user_path(id: comment.user_id)

Upvotes: 0

Related Questions