27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

490 CHAPTER 17 Engines<br />

NOTE We’re purposely not including validations in this action. This is<br />

mainly to keep the chapter short, but it’s also a good exercise to be left to<br />

you. Remember to write tests that the validations work before implementing<br />

the code!<br />

When you run your spec again using bin/rspec spec/integration/topics_spec.rb,<br />

you’ll get this error:<br />

AbstractController::ActionNotFound:<br />

The action 'show' could not be found for Forem::TopicsController<br />

You’re getting closer to having your spec pass! When it clicks the Create Topic button,<br />

it’s now going through the create action successfully and is then redirecting to the<br />

show action, which you need to define now.<br />

17.5.7 The show action<br />

The show action in Forem::TopicsController will be responsible for displaying a<br />

topic and its posts. Your first step will be defining this action, which you can do by putting<br />

this code inside app/controllers/forem/topics_controller.rb underneath the<br />

create action:<br />

def show<br />

@topic = Forem::Topic.find(params[:id])<br />

end<br />

You’re then going to need to create the view for this action, which goes at app/views/<br />

forem/topics/show.html.erb and contains the short bit of code in the following listing.<br />

Listing 17.8 app/views/forem/topics/show.html.erb<br />

<br />

<br />

<br />

"forem/posts/post", :collection => @topic.posts %><br />

<br />

<br />

You’re using a long form of render here again to render the app/views/forem/posts/<br />

_post.html.erb partial for each of the posts. The shorter version goes like this:<br />

<br />

Unfortunately, due to the namespacing on your model, Rails will attempt to render<br />

the app/views/forem/forem/posts/_post.html.erb (double “forem”) partial instead.<br />

You therefore have to be explicit. A short note: the long form’s syntax was how it used<br />

to be done in earlier versions of Rails.<br />

The partial that it renders hasn’t been created yet, and so this will be your next<br />

step. Let’s create a new file at app/views/forem/posts/_post.html.erb and fill it with<br />

this content:<br />

<br />

Written at

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!