0

I've just implemented friendly_id for my post urls but creating comments error with "No route matches {:action=>"show", :controller=>"posts", :id=>nil} missing required keys: [:id]"

comments controller

before_filter :authenticate_user!

def create
    @comment = Comment.new(comment_params)
    @comment.post_id = params[:post_id]
    @comment.user_id = current_user.id

    @comment.save

    redirect_to post_path(@comment.post)
end

def comment_params
    params.require(:comment).permit(:user_id, :body)
end

I've tested removing friendly_id and it's definately this messing with it. I assume it's because creating a comment directs to url/posts/post-name/comments (friendly_id) when it's looking for url/posts/post-id/comments.

Any ideas?

1 Answers1

0

You aren't passing a post_id when creating a comment. The error is stating that the :id is nil because params[:post_id] is not being sent. In your comment form, be sure to set the post_id for new records.

Joe Kennedy
  • 9,365
  • 7
  • 41
  • 55
  • Thank you for the help, could you give an example of this? Still very new to ruby & rails. Is it similar to setting a hidden field in the actual comment form? –  Apr 26 '14 at 08:02
  • That would absolutely be one way to do it. `f.hidden_field :post_id, value: @post.id` where `@post` is the post you'd like to attach your comment to. – Joe Kennedy Apr 26 '14 at 08:04