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.

506 CHAPTER 17 Engines<br />

This is the element in which you’ll be displaying the user on the page, with the content<br />

being the name of the user that you set up in the sign_in! method. This user<br />

association is actually going to be set both on the topic and its first post. Right now this<br />

element doesn’t exist, and so if you were to run this test it would fail.<br />

Your first step is to associate the topic to a user when you create the topic in<br />

Forem::TopicsController. You can do this by changing this line of the create action<br />

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

to these two lines:<br />

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

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

This will set up the user association for the topic, passing it through with the other<br />

parameters inside params[:topic]. This will not set up the first post for this topic to<br />

have this user associated, which is what you need in order to make your test pass. To<br />

do this, create a before_save callback in the Forem::Topic by using the code from<br />

the following listing, placing it under the accepts_nested_attributes_for :post<br />

line in the model.<br />

Listing 17.16 app/models/forem/topic.rb<br />

before_save :set_post_user<br />

private<br />

def set_post_user<br />

self.posts.first.user = self.user<br />

end<br />

With the user association now set for a topic’s first post, you can display the user’s<br />

name along with the post by putting this line under the small tag already in app/<br />

views/forem/posts/_post.html.erb:<br />

By <br />

Here you use Forem::Engine.user_name, which is the method that you use to display<br />

the user’s name. In this case, it would display the login attribute. When you run bin/<br />

rspec spec/integration/topics_spec.rb, all your tests will pass:<br />

3 examples, 0 failures<br />

That was easy! When a topic is created, the topic and its first post will now belong to<br />

the user who created it. Remember: your User model is in another castle, or rather, it<br />

is in your application, and so this is very cool.<br />

Now you’ll need to check that users are logged in before they create posts too, and<br />

then associate the posts to the users upon creation.<br />

17.7.5 Post authentication<br />

You’ve got the authenticate_forem_user! method defined in the Forem<br />

::ApplicationController, and so it’s available for all controllers that inherit from it.

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

Saved successfully!

Ooh no, something went wrong!