concept topic in category rails

appears as: topics, topic, topics, topic
Rails 3 in Action

This is an excerpt from Manning's book Rails 3 in Action.

In this section, you’ve created an interface for creating topics and their first post, which is the first feature of your engine and a well-tested one at that. You’ve seen how to use fields_for to yet again create nested resources. You first saw that back in chapter 8. You’ve also seen the :counter_cache option for belongs_to that you can use to cache the count of an association, so that you don’t have to perform another query to get that number. That’s a potential lifesaver if you’re displaying a lot of objects at once and want to know an association’s count on all of them, like in your topics view.

In the next section, you’re going to add the ability to add posts to a topic, because what are topics without posts?

17.6. Adding more posts to topics

A forum system without a way for users to reply to topics is nearly useless. The whole point of having topics is so that users can reply to them and keep the topic of conversation going for as long as they wish!

The feature that you’re about to develop will let people add these replies to existing topics. They’ll click a New Reply link on a topic, fill in the post text, and click the submit button. They should then see their post within the list of posts in the topic. Simple, really!

In order to reply to a topic, you’re going to need to create one. You initialize a new Forem::Topic object by using Forem::Topic.new and then build a post for it. This means that when you navigate to the topic’s page, then you’ll see a post that will have a Reply link for you to click. You’ll put the test underneath the before by using the code in the following listing.

Listing 17.10. spec/integration/posts_spec.rb

In this test, you go to topics_path and click the First Topic! link. Then within a post, you click the Reply link, which will take you to the form to create a new reply to this topic. On this new page, you fill in the text with a short message and click the Create Post button to create a new post. Once this is done, you’ll be taken to the create action in Forem::PostsController, which will set the flash[:notice] to be “Post has been created!” and then redirect you back to the topic’s page, where you should see First Reply! within a post.

resources :topics do
  resources :posts
end