WuJo WuJo - 1 year ago 46
Ruby Question

editing nested resources gives exception

I have following problem. I'm writting simple blog for learn rails. My project is mostly based on scaffolds. In simplification, I have 2 models: Post and Comment. Post has many comments.

I'm using nested resources:

resources :posts do
resources :comments

In post's show action i'm listing all post's comments and I have form for creating new comments, and it all works ok. But I have problem when I want to edit comments, I get "NoMethodError in Comments#edit".

undefined method `comment_path' for #<#<Class:0x007fe554980ad0>:0x007fe5569fedc0>
Did you mean? font_path

Rails guides doesn't help me.

My code:

in PostController

def show
@comments = @post.comments
@comment = Comment.new

in post's view(through comment's partial for listing comments)

<%= link_to 'Edit', edit_post_comment_path(@post, comment)%>

in CommentController

def edit

in comment's view

<%= render 'form' %>

and partial form

<%= form_for([@post, @comment]) do |f| %>

<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content %>
<div class="actions">
<%= f.submit %>
<% end %>

This line

<%= form_for([@post, @comment]) do |f| %>

gives me an exception.

Answer Source

It looks like @post is nil so [@post, @comment] is actually being evaluated as [nil, @comment] which is trying to map to the comments_path route.

Make sure you assign @post in your controller: @post = Post.find(...)