开发者

Simple posts / comments route in rails 3

开发者 https://www.devze.com 2023-01-15 03:45 出处:网络
I\'m trying to write a route that captures the one-to-many relationship between posts and comments in your average blog

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开发者_StackOverflow 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?


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 )

0

精彩评论

暂无评论...
验证码 换一张
取 消