Search code examples
ruby-on-railsrubyforumnested-resources

Trouble with multiple resources on creating message board


I'm working on a message board for my application and it has the typical three resources to make it all work: Forums, Topics and Posts. The routes are defined as so:

resources :forums do
    resources :topics do
        resources :posts
    end
end

Topics have posts defined as a nested resource, as when you create a new topic, a new post is created to start the thread off. So that all works well. But I'm stuck on the Topic's 'Show' page. On that page, like any message board model, after showing all the posts there is a form at the bottom to add a new post / reply. Once the post's create action is triggered, it will redirect back to the topic, etc. Implementing that form is what I am tripped up on.

Normally I would think of something like this...

<%= form_for([@topic, @post]) do |f| %>
    ...
<% end %>

...only the page returns an "undefined method `topic_posts_path'" error. And that's not surprising, as taking a look at rake routes returns this as the create action for Posts.

forum_topic_posts POST   /forums/:forum_id/topics/:topic_id/posts(.:format)     {:controller=>"posts", :action=>"create"}

Figured I would try <%= form_for([@forum, @topic, @post]) do |f| %> in the form_for, but just returned me the same error. Figuring I needed to give it the actual path instead, I gave <%= form_for :url => forum_topic_posts_url do |f| %> a try, but it didn't care for that either.

After Googling, most forum tutorials were outdated or stopped short of adding the new posts form on the topic page, only showing nearly all the stuff I worked out already.

The only other thing I was able to turn up suggested not nesting resources three or more levels down, but stopped short of 'why', much less suggest a suitable alternative. Besides, the route path above seems like the most logical path for this kind of action.

So how do I accomplish getting the Post form to work on the Topic Show page in this kind of setup?


Solution

  • When you try "form_for([@forum, @topic, @post])" you have set @forum variable in controller?