dimitry_n
dimitry_n

Reputation: 3019

Nested resources - undefined method `comments_path'

I'm working on a forum app which has 4 models: Users, Boards, Topics and Comments. My routes are:

resources :users do 
 resources :boards ### 'boards' contain 'topics'
 resources :topics ### 'topics' are similar to 'posts'
 resources :comments 
end

resources :topics do 
 resources :comments
end

I call a link_to method in my posts#show action with a new_topic_comment_path and pass the @topic variable as follows:

<%=link_to "Leave a reply", new_topic_comment_path(@topic) %>

and in my comments#new view, I have the following form:

<%=form_for @comment do |f| %>
<%=f.label :your_comment %>
<%=f.text_field :body %>
<%=f.submit "Post" %>
<%end%>

and here is my comments#new action:

def new
    @comment = Comment.new
    @topic = Topic.find(params[:topic_id])
end

when comments#new is loaded from the topics#show view, I get an error saying undefined method "comments_path"

Upvotes: 1

Views: 1326

Answers (2)

dimitry_n
dimitry_n

Reputation: 3019

Got it! When using nested resources routing such as foo/bar, I need to pass two variables to the form in comments#new view. So instead of:

<%= form_for @bar do |f| %>
...
<% end %>

do

<%= form_for [@foo, @bar] do |f| %>
...
<% end %>

Upvotes: 3

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

Try

form_for [@topic, @comment] do |f|

More information here

Upvotes: 0

Related Questions