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.

to these lines:<br />

Classes outside your control<br />

params[:post].merge!(:user => current_user)<br />

@post = @topic.posts.create(params[:post])<br />

We’re putting this on separate lines to make the second line a little shorter for readability.<br />

When you run bin/rspec spec/integration/posts_spec.rb again, you’ll see<br />

that it all passes:<br />

2 examples, 0 failures<br />

Now you’re authenticating users before they can create new posts, and then assigning<br />

them as the user when they’re authenticated. That means you’re done here and<br />

should run all the specs to make sure everything works with a quick run of bin/rspec<br />

spec. You should see this:<br />

7 examples, 0 failures<br />

Good to see! Let’s make a commit:<br />

git add .<br />

git commit -m "Authenticate users and link them to posts"<br />

You’ve now got a pretty good starting feature set for your engine. Users are able to create<br />

topics and posts, but only if they’re authenticated in the parent application, and<br />

that’s a good start. You could generate further features, such as editing topics and<br />

posts, but that’s an exercise best left to you. 20<br />

One thing you’ve still got left to do is fix up the second placeholder in app/views/<br />

topics/index.html.erb, which shows the last post for a topic. You’ll do this now; it’ll<br />

only take a moment.<br />

17.7.6 Showing the last post<br />

Currently in app/views/topics/index.html.erb you have this line:<br />

last post was at TIME by USER<br />

It would be extremely helpful to your users if this returned useful information rather<br />

than a placeholder. You’ve finished linking posts and users, and so now is a great time<br />

to fix this placeholder up.<br />

To begin with, you’re going to add a test to spec/integration/posts_spec.rb to<br />

ensure that you do indeed see the last post’s information. It’s the same function displayed<br />

to unauthenticated users as it is authenticated users, but you’re going to need<br />

current_user set by either sign_out! or sign_in!. Therefore, you’ll put this test<br />

inside the context "unauthenticated users" block to make things easy. The code for<br />

this test is shown in the following listing.<br />

20 Additionally, this is a long enough chapter already!<br />

509

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

Saved successfully!

Ooh no, something went wrong!