Soyong
Soyong

Reputation: 188

Associations in Ruby on Rails 4

I've got a question to associations in rails. I am trying to create a comment for a post which has a subject. So my routs file looks like this:

resources :subjects do
  resources :post do
    resources :comments
  end
end

Now am I trying to create a form in the show.html.erb file of the post so someone can create a comment. I've tried it this way which I found in the rails guide:

'posts/show.html.erb'

<%= form_for {[@post, @post.comments.build]} do |f| %>
//fill in form
<% end %>

'posts.controller.rb'

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

But this gives me an error. If you need any other codeparts, feel free to ask.

Error Message

ActionView::Template::Error (undefined method `post_comments_path' for #<#<Class:0x007f9a4429d5e8>:0x007f9a42c01fc8>):
 8:   <strong>Text:</strong>
 9:   <%= @post.text %>
10: </p>
11: <%= form_for ([@post, @post.comments.build]) do |f| %>
12:     <p>
13:       <%= f.label :text %><br>
14:       <%= f.text_area :text %>

Upvotes: 1

Views: 42

Answers (1)

Jarred
Jarred

Reputation: 2014

Those paths are grouped under resources :subjects, so your path will be subjects_post_comments_path, or if you prefer to use polymorphic paths it will be [@subjects, @post, @post.comments.build].

You can run rake routes | grep comments to see the paths for all of your comments routes.

Upvotes: 2

Related Questions