views:

24

answers:

1

I'm trying to write a route that captures the one-to-many relationship between posts and comments in your average blog

What I have currently is a post.rb

class Post < ActiveRecord::Base
  has_many :comments
end

followed by a comment.rb (among all the other db setups including post_id:integer for comment)

class Comment < ActiveRecord::Base
  belongs_to :post
end

In the routes I'm trying to use

resources :posts do
  resources :comments
end

but I'm not having any luck - any help from a rails 3 expert?

Edit

When I hit the "show" action of my post controller via this url

http://localhost:3000/posts/3

I get a routing error

No route matches {:controller=>"comments", :action=>"create"}

This is because of my comments form in the show template of my post

<% form_for Comment.new do |f| %>
<p>
  <%= f.label :body, "new comment" %><br>
  <%= f.text_area :body %>
</p>
<p><%= f.submit "add comment" %></p>
<% end %>

Do I need to alter my form because before this alteration to the routes when I did a simple view source the action pointed to /comments/{id}

Edit #2

I did notice that after I altered my routes to look like this

 resources :comments
  resources :posts

  resources :posts do
    resources :comments
  end

I get everything working except that my created comment doesn't know the post_id (in MySQL the comment is persisted yet it doesn't know the post it belongs_to)

Could this maybe be my form then?

+2  A: 

You Comment resources is defined as a nested resource not as independent resource,

so the path generated require the posts information as well. so change the form_for statement to

form_for [@post,Comment.new] do |f|

http://guides.rubyonrails.org/routing.html , read this to understand more

and this http://railscasts.com/episodes/139-nested-resources ( uses very old version of rails )

Rishav Rastogi
this fixed my form in the show template, but is it "valid" to have all 3 resources defined as I do in the example above? If not what would you suggest?
Toran Billups
the first way is the rails way, but sometimes its get fairly complicated with nested resources, so people switch to what you have done. So until you know better use the rails way.
Rishav Rastogi
and you don't need not define "resources :posts" again. With #1 nested resource way its easier to manage association and authorization within models. but in #2 you ll have manage that. manually. so take your pick
Rishav Rastogi