Contents

Foreword

My former company (CD Baby) was one of the first to loudly switch to Ruby on Rails, and then even more loudly switch back to PHP (Google me to read about the drama). This book by Michael Hartl came so highly recommended that I had to try it, and the Ruby on Rails Tutorial is what I used to switch back to Rails again.

Though I’ve worked my way through many Rails books, this is the one that finally made me “get” it. Everything is done very much “the Rails way”—a way that felt very unnatural to me before, but now after doing this book finally feels natural. This is also the only Rails book that does test-driven development the entire time, an approach highly recommended by the experts but which has never been so clearly demonstrated before. Finally, by including Git, GitHub, and Heroku in the demo examples, the author really gives you a feel for what it’s like to do a real-world project. The tutorial’s code examples are not in isolation.

The linear narrative is such a great format. Personally, I powered through the Rails Tutorial in three long days, doing all the examples and challenges at the end of each chapter. Do it from start to finish, without jumping around, and you’ll get the ultimate benefit.

Enjoy!

Derek Sivers (sivers.org)
Formerly: Founder, CD Baby
Currently: Founder, Thoughts Ltd.

Acknowledgments

The Ruby on Rails Tutorial owes a lot to my previous Rails book, RailsSpace, and hence to my coauthor Aurelius Prochazka. I’d like to thank Aure both for the work he did on that book and for his support of this one. I’d also like to thank Debra Williams Cauley, my editor on both RailsSpace and the Ruby on Rails Tutorial; as long as she keeps taking me to baseball games, I’ll keep writing books for her.

I’d like to acknowledge a long list of Rubyists who have taught and inspired me over the years: David Heinemeier Hansson, Yehuda Katz, Carl Lerche, Jeremy Kemper, Xavier Noria, Ryan Bates, Geoffrey Grosenbach, Peter Cooper, Matt Aimonetti, Gregg Pollack, Wayne E. Seguin, Amy Hoy, Dave Chelimsky, Pat Maddox, Tom Preston-Werner, Chris Wanstrath, Chad Fowler, Josh Susser, Obie Fernandez, Ian McFarland, Steven Bristol, Wolfram Arnold, Alex Chaffee, Giles Bowkett, Evan Dorn, Long Nguyen, James Lindenbaum, Adam Wiggins, Tikhon Bernstam, Ron Evans, Wyatt Greene, Miles Forrest, the good people at Pivotal Labs, the Heroku gang, the thoughtbot guys, and the GitHub crew. Finally, many, many readers—far too many to list—have contributed a huge number of bug reports and suggestions during the writing of this book, and I gratefully acknowledge their help in making it as good as it can be.

Michael Hartl is the author of the Ruby on Rails Tutorial, the leading introduction to web development with Ruby on Rails. His prior experience includes writing and developing RailsSpace, an extremely obsolete Rails tutorial book, and developing Insoshi, a once-popular and now-obsolete social networking platform in Ruby on Rails. In 2011, Michael received a Ruby Hero Award for his contributions to the Ruby community. He is a graduate of Harvard College, has a Ph.D. in Physics from Caltech, and is an alumnus of the Y Combinator entrepreneur program.

Ruby on Rails Tutorial: Learn Rails by Example. Copyright © 2012 by Michael Hartl. All source code in the Ruby on Rails Tutorial is available jointly under the MIT License and the Beerware License.

   Copyright (c) 2012 Michael Hartl

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
/*
* ------------------------------------------------------------
* "THE BEERWARE LICENSE" (Revision 42):
* Michael Hartl wrote this code. As long as you retain this
* notice, you can do whatever you want with this stuff. If we
* meet someday, and you think this stuff is worth it, you can
* buy me a beer in return.
* ------------------------------------------------------------
*/

Chapter 10 User microposts

Chapter 9 saw the completion of the REST actions for the Users resource, so the time has finally come to add a second full resource: user microposts.1 These are short messages associated with a particular user, first seen in larval form in Chapter 2. In this chapter, we will make a full-strength version of the sketch from Section 2.3 by constructing the Micropost data model, associating it with the User model using the has_many and belongs_to methods, and then making the forms and partials needed to manipulate and display the results. In Chapter 11, we’ll complete our tiny Twitter clone by adding the notion of following users in order to receive a feed of their microposts.

If you’re using Git for version control, I suggest making a topic branch as usual:

$git checkout -b user-microposts  10.1 A Micropost model We begin the Microposts resource by creating a Micropost model, which captures the essential characteristics of microposts. What follows builds on the work from Section 2.3; as with the model in that section, our new Micropost model will include data validations and an association with the User model. Unlike that model, the present Micropost model will be fully tested, and will also have a default ordering and automatic destruction if its parent user is destroyed. 10.1.1 The basic model The Micropost model needs only two attributes: a content attribute to hold the micropost’s content,2 and a user_id to associate a micropost with a particular user. As with the case of the User model (Listing 6.1), we generate it using generate model: $ rails generate model Micropost content:string user_id:integer


This produces a migration to create a microposts table in the database (Listing 10.1); compare it to the analogous migration for the users table from Listing 6.2.

Listing 10.1. The Micropost migration. (Note the index on user_id and created_at.)
db/migrate/[timestamp]_create_microposts.rb
class CreateMicroposts < ActiveRecord::Migration
def change
create_table :microposts do |t|
t.string :content
t.integer :user_id

t.timestamps
end
end
end


Note that, since we expect to retrieve all the microposts associated with a given user id in reverse order of creation, Listing 10.1 adds an index (Box 6.2) on the user_id and created_at columns:

add_index :microposts, [:user_id, :created_at]


By including both the user_id and created_at columns as an array, we arrange for Rails to create a multiple key index, which means that Active Record uses both keys at the same time. Note also the t.timestamps line, which (as mentioned in Section 6.1.1) adds the magic created_at and updated_at columns. We’ll put the created_at column to work in Section 10.1.4 and Section 10.2.1.

We’ll start with some minimal tests for the Micropost model based on the analogous tests for the User model (Listing 6.8). In particular, we verify that a micropost object responds to the content and user_id attributes, as shown in Listing 10.2.

Listing 10.2. The initial Micropost spec.
spec/models/micropost_spec.rb
require 'spec_helper'

describe Micropost do

let(:user) { FactoryGirl.create(:user) }
before do
# This code is wrong!
@micropost = Micropost.new(content: "Lorem ipsum", user_id: user.id)
end

subject { @micropost }

it { should respond_to(:content) }
it { should respond_to(:user_id) }
end


We can get these tests to pass by running the microposts migration and preparing the test database:

$bundle exec rake db:migrate$ bundle exec rake db:test:prepare


The result is a Micropost model with the structure shown in Figure 10.1.

You should verify that the tests pass:



10.1.4 Micropost refinements

The test in Listing 10.7 of the has_many association doesn’t test for much—it merely verifies the existence of a microposts attribute. In this section, we’ll add ordering and dependency to microposts, while also testing that the user.microposts method actually returns an array of microposts.

We will need to construct some microposts in the User model test, which means that we should make a micropost factory at this point. To do this, we need a way to make an association in Factory Girl. Happily, this is easy, as seen in Listing 10.10.

Listing 10.10. The complete factory file, including a new factory for microposts.
spec/factories.rb
FactoryGirl.define do
factory :user do
sequence(:name)  { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com"}

end
end

factory :micropost do
content "Lorem ipsum"
user
end
end


Here we tell Factory Girl about the micropost’s associated user just by including a user in the definition of the factory:

factory :micropost do
content "Lorem ipsum"
user
end


As we’ll see in the next section, this allows us to define factory microposts as follows:

FactoryGirl.create(:micropost, user: @user, created_at: 1.day.ago)


Default scope

By default, using user.microposts to pull a user’s microposts from the database makes no guarantees about the order of the posts, but (following the convention of blogs and Twitter) we want the microposts to come out in reverse order of when they were created, i.e., most recent first. To test this ordering, we first create a couple of microposts as follows:

FactoryGirl.create(:micropost, user: @user, created_at: 1.day.ago)
FactoryGirl.create(:micropost, user: @user, created_at: 1.hour.ago)


Here we indicate (using the time helpers discussed in Box 8.1) that the second post was created more recently, i.e., 1.hour.ago, while the first post was created 1.day.ago. Note how convenient the use of Factory Girl is: not only can we assign the user using mass assignment (since factories bypass attr_accessible), we can also set created_at manually, which Active Record won’t allow us to do. (Recall that created_at and updated_at are “magic” columns, automatically set to the proper creation and update timestamps, so any explicit initialization values are overwritten by the magic.)

Most database adapters (including the one for SQLite) return the microposts in order of their ids, so we can arrange for an initial test that almost certainly fails using the code in Listing 10.11. This uses the let! (read “let bang”) method in place of let; the reason is that let variables are lazy, meaning that they only spring into existence when referenced. The problem is that we want the microposts to exist immediately, so that the timestamps are in the right order and so that @user.microposts isn’t empty. We accomplish this with let!, which forces the corresponding varible to come into existence.

Listing 10.11. Testing the order of a user’s microposts.
spec/models/user_spec.rb
require 'spec_helper'

describe User do
.
.
.
describe "micropost associations" do

before { @user.save }
let!(:older_micropost) do
FactoryGirl.create(:micropost, user: @user, created_at: 1.day.ago)
end
FactoryGirl.create(:micropost, user: @user, created_at: 1.hour.ago)
end

it "should have the right microposts in the right order" do
end
end
end


The key line here is

@user.microposts.should == [newer_micropost, older_micropost]


indicating that the posts should be ordered newest first. This should fail because by default the posts will be ordered by id, i.e., [older_micropost, newer_micropost]. This test also verifies the basic correctness of the has_many association itself, by checking (as indicated in Table 10.1) that user.microposts is an array of microposts.

To get the ordering test to pass, we use a Rails facility called default_scope with an :order parameter, as shown in Listing 10.12. (This is our first example of the notion of scope. We will learn about scope in a more general context in Chapter 11.)

Listing 10.12. Ordering the microposts with default_scope.
app/models/micropost.rb
class Micropost < ActiveRecord::Base
.
.
.
default_scope order: 'microposts.created_at DESC'
end


The order here is ’microposts.created_at DESC’, where DESC is SQL for “descending”, i.e., in descending order from newest to oldest.

Dependent: destroy

Apart from proper ordering, there is a second refinement we’d like to add to microposts. Recall from Section 9.4 that site administrators have the power to destroy users. It stands to reason that, if a user is destroyed, the user’s microposts should be destroyed as well. We can test for this by first destroying a micropost’s user and then verifying that the associated microposts are no longer in the database (Listing 10.13).

Listing 10.13. Testing that microposts are destroyed when users are.
spec/models/user_spec.rb
require 'spec_helper'

describe User do
.
.
.
describe "micropost associations" do

before { @user.save }
let!(:older_micropost) do
FactoryGirl.create(:micropost, user: @user, created_at: 1.day.ago)
end
FactoryGirl.create(:micropost, user: @user, created_at: 1.hour.ago)
end
.
.
.
it "should destroy associated microposts" do
microposts = @user.microposts
@user.destroy
microposts.each do |micropost|
Micropost.find_by_id(micropost.id).should be_nil
end
end
end
.
.
.
end


Here we have used Micropost.find_by_id, which returns nil if the record is not found, whereas Micropost.find raises an exception on failure, which is a bit harder to test for. (In case you’re curious,

lambda do
Micropost.find(micropost.id)
end.should raise_error(ActiveRecord::RecordNotFound)


does the trick in this case.)

The application code to get Listing 10.13 to pass is less than one line; in fact, it’s just an option to the has_many association method, as shown in Listing 10.14.

Listing 10.14. Ensuring that a user’s microposts are destroyed along with the user.
app/models/user.rb
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
.
.
.
end


Here the option dependent: :destroy in

has_many :microposts, dependent: :destroy


arranges for the dependent microposts (i.e., the ones belonging to the given user) to be destroyed when the user itself is destroyed. This prevents userless microposts from being stranded in the database when admins choose to remove users from the system.

With that, the final form of the user/micropost association is in place, and all the tests should be passing:

$bundle exec rspec spec/  10.1.5 Content validations Before leaving the Micropost model, we’ll add validations for the micropost content (following the example from Section 2.3.2). Like the user_id, the content attribute must be present, and it is further constrained to be no longer than 140 characters, making it an honest micropost. The tests generally follow the examples from the User model validation tests in Section 6.2, as shown in Listing 10.15. Listing 10.15. Tests for the Micropost model validations. spec/models/micropost_spec.rb require 'spec_helper' describe Micropost do let(:user) { FactoryGirl.create(:user) } before { @micropost = user.microposts.build(content: "Lorem ipsum") } . . . describe "when user_id is not present" do before { @micropost.user_id = nil } it { should_not be_valid } end describe "with blank content" do before { @micropost.content = " " } it { should_not be_valid } end describe "with content that is too long" do before { @micropost.content = "a" * 141 } it { should_not be_valid } end end  As in Section 6.2, the code in Listing 10.15 uses string multiplication to test the micropost length validation: $ rails console
>> "a" * 10
=> "aaaaaaaaaa"
>> "a" * 141
=> "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"


The application code is a one-liner:

validates :content, presence: true, length: { maximum: 140 }


The resulting Micropost model is shown in Listing 10.16.

Listing 10.16. The Micropost model validations.
app/models/micropost.rb
class Micropost < ActiveRecord::Base
attr_accessible :content

belongs_to :user

validates :content, presence: true, length: { maximum: 140 }
validates :user_id, presence: true

default_scope order: 'microposts.created_at DESC'
end


10.2 Showing microposts

Although we don’t yet have a way to create microposts through the web—that comes in Section 10.3.2—that won’t stop us from displaying them (and testing that display). Following Twitter’s lead, we’ll plan to display a user’s microposts not on a separate microposts index page, but rather directly on the user show page itself, as mocked up in Figure 10.4. We’ll start with fairly simple ERb templates for adding a micropost display to the user profile, and then we’ll add microposts to the sample data populator from Section 9.3.2 so that we have something to display.

As with the discussion of the signin machinery in Section 8.2.1, Section 10.2.1 will often push several elements onto the stack at a time, and then pop them off one by one. If you start getting bogged down, be patient; there’s some nice payoff in Section 10.2.2.

10.2.1 Augmenting the user show page

We begin with tests for displaying the user’s microposts, which we’ll create in the request spec for Users. Our strategy is to create a couple of factory microposts associated with the user, and then verify that the show page contains each post’s content. We’ll also verify that, as in Figure 10.4, the total number of microposts also gets displayed.

We can create the posts with the let method, but as in Listing 10.11 we want the association to exist immediately so that the posts appear on the user show page. To accomplish this, we use the let! variant:

let(:user) { FactoryGirl.create(:user) }
let!(:m1) { FactoryGirl.create(:micropost, user: user, content: "Foo") }
let!(:m2) { FactoryGirl.create(:micropost, user: user, content: "Bar") }

before { visit user_path(user) }


With the microposts so defined, we can test for their appearance on the profile page using the code in Listing 10.17.

Listing 10.17. A test for showing microposts on the user show page.
spec/requests/user_pages_spec.rb
require 'spec_helper'

describe "User pages" do
.
.
.
describe "profile page" do
let(:user) { FactoryGirl.create(:user) }
let!(:m1) { FactoryGirl.create(:micropost, user: user, content: "Foo") }
let!(:m2) { FactoryGirl.create(:micropost, user: user, content: "Bar") }

before { visit user_path(user) }

it { should have_selector('h1',    text: user.name) }
it { should have_selector('title', text: user.name) }

describe "microposts" do
it { should have_content(m1.content) }
it { should have_content(m2.content) }
it { should have_content(user.microposts.count) }
end
end
.
.
.
end


Note here that we can use the count method through the association:

user.microposts.count


The association count method is smart, and performs the count directly in the database. In particular, it does not pull all the microposts out of the database and then call length on the resulting array, as this could become inefficient as the number of microposts grew. Instead, it asks the database to count the microposts with the given user_id. In the unlikely event that finding the count is still a bottleneck in your application, you can make it even faster with a counter cache.

Although the tests in Listing 10.17 won’t pass until Listing 10.19, we’ll get started on the application code by inserting a table of microposts into the user profile page, as shown in Listing 10.18.3

Listing 10.18. Adding microposts to the user show page.
app/views/users/show.html.erb
<table class="profile">
<tr>
<td class="main">
.
.
.
<% if @user.microposts.any? %>
<table class="microposts">
<%= render @microposts %>
</table>
<%= will_paginate @microposts %>
<% end %>
</td>
<td class="sidebar round">
<strong>Name</strong> <%= @user.name %><br />
<strong>URL</strong> <%= link_to user_path(@user), @user %><br />
<strong>Microposts</strong> <%= @user.microposts.count %>
</td>
</tr>
</table>


We’ll deal with the microposts table momentarily, but there are several other things to note first. One is the use of any? in the code

@user.microposts.any?


We saw this construction before in Listing 7.22; it returns true if there are any microposts and false otherwise. This makes sure that an empty table won’t be displayed when the user has no microposts.

You’ll also note from Listing 10.18 that we’ve preemptively added pagination for microposts through

<%= will_paginate @microposts %>


If you compare this with the analogous line on the user index page, Listing 9.34, you’ll see that before we had just

<%= will_paginate %>


This worked because, in the context of the Users controller, will_paginate assumes the existence of an instance variable called @users (which, as we saw in Section 9.3.3, should be of class WillPaginate::Collection). In the present case, since we are still in the Users controller but want to paginate microposts instead, we pass an explicit @microposts variable to will_paginate. Of course, this means that we will have to define such a variable in the user show action (Listing 10.20).

Finally, note that we have taken this opportunity to add a count of the current number of microposts to the profile sidebar:

<td class="sidebar round">
<strong>Name</strong> <%= @user.name %><br />
<strong>URL</strong> <%= link_to user_path(@user), @user %><br />
<strong>Microposts</strong> <%= @user.microposts.count %>
</td>


As noted, @user.microposts.count is the analogue of the User.count method, except that it counts the microposts belonging to a given user through the user/micropost association.

Now for the microposts table itself:

<table class="microposts">
<%= render @microposts %>
</table>


This code is responsible for generating the table of microposts, but you can see that it just defers the heavy lifting to a micropost partial. We saw in Section 9.3.4 that the code

<%= render @users %>


automatically renders each of the users in the @users variable using the _user.html.erb partial. Similarly, the code

<%= render @microposts %>


does exactly the same thing for microposts. This means that we must define a _micropost.html.erb partial (along with a micropost views directory), as shown in Listing 10.19.

Listing 10.19. A partial for showing a single micropost.
app/views/microposts/_micropost.html.erb
<tr>
<td class="micropost">
<span class="content"><%= micropost.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
</span>
</td>
</tr>


This uses the awesome time_ago_in_words helper method, whose effect we will see in Section 10.2.2.

Thus far, despite defining all the relevant ERb templates, the test in Listing 10.17 should have been failing for want of an @microposts variable. We can get it to pass with Listing 10.20.

Listing 10.20. Adding an @microposts instance variable to the user show action.
app/controllers/users_controller.rb
class UsersController < ApplicationController
.
.
.
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
end
end


Notice here how clever paginate is—it even works with the microposts association, converting the array into a WillPaginate::Collection object on the fly.

Upon adding the CSS from Listing 10.21 to our layout.css.scss stylesheet,4 we can get a look at our new user profile page in Figure 10.5. It’s rather… disappointing. Of course, this is because there are not currently any microposts. It’s time to change that.

Listing 10.21. The CSS for microposts (including all the CSS for this chapter).
app/assets/stylesheets/layout.css.scss
.
.
.
h1.micropost {
margin-bottom: 0.3em;
}

table.microposts {
margin-top: 1em;

tr {
height: 70px;

&:nth-child(2n) td, tbody tr.even td {
background: white
}

td.gravatar {
border-top: 1px solid #ccc;
vertical-align: top;
width: 50px;
}

td.micropost {
border-top: 1px solid #ccc;
vertical-align: top;

span.timestamp {
display: block;
font-size: 85%;
color: #666;
}
}
}
}

div.user_info {
img {
}
a {
text-decoration: none;
}
span.user_name {
position: absolute;
}
span.microposts {
font-size: 80%;
}
}

form.new_micropost {
margin-bottom: 2em;

textarea {
height: 4em;
margin-bottom: 0;
}
}


10.2.2 Sample microposts

With all the work making templates for user microposts in Section 10.2.1, the ending was rather anticlimactic. We can rectify this sad situation by adding microposts to the sample populator from Section 9.3.2. Adding sample microposts for all the users actually takes a rather long time, so first we’ll select just the first six users5 using the :limit option to the User.all method:6

users = User.all(limit: 6)


We then make 50 microposts for each user (plenty to overflow the pagination limit of 30), generating sample content for each micropost using the Faker gem’s handy Lorem.sentence method. (Faker::Lorem.sentence returns lorem ipsum text; as noted in Chapter 6, lorem ipsum has a fascinating back story.) The result is the new sample data populator shown in Listing 10.22.

Listing 10.22. Adding microposts to the sample data.
lib/tasks/sample_data.rake
namespace :db do
desc "Fill database with sample data"
.
.
.
users = User.all(limit: 6)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
end
end


Of course, to generate the new sample data we have to run the db:populate Rake task:

$bundle exec rake db:populate$ bundle exec rake db:test:prepare


With that, we are in a position to enjoy the fruits of our Section 10.2.1 labors by displaying information for each micropost.7 Figure 10.6 shows the user profile page for the first (signed-in) user, while Figure 10.7 shows the profile for a second user. Finally, Figure 10.8 shows the second page of microposts for the first user, along with the pagination links at the bottom of the display. In all three cases, observe that each micropost display indicates the time since it was created (e.g., “Posted 1 minute ago.”); this is the work of the time_ago_in_words method from Listing 10.19. If you wait a couple minutes and reload the pages, you’ll see how the text gets automatically updated based on the new time.

10.3 Manipulating microposts

Having finished both the data modeling and display templates for microposts, we now turn our attention to the interface for creating them through the web. The result will be our third example of using an HTML form to create a resource—in this case, a Microposts resource.8 In this section, we’ll also see the first hint of a status feed—a notion brought to full fruition in Chapter 11. Finally, as with users, we’ll make it possible to destroy microposts through the web.

There is one break with past convention worth noting: the interface to the Microposts resource will run principally through the Users and StaticPages controllers, rather than relying on a controller of its own. This means that the routes for the Microposts resource are unusually simple, as seen in Listing 10.23. The code in Listing 10.23 leads in turn to the RESTful routes shown in Table 10.2, which is a small subset of the full set of routes seen in Table 2.3. Of course, this simplicity is a sign of being more advanced, not less—we’ve come a long way since our reliance on scaffolding in Chapter 2, and we no longer need most of its complexity.

Listing 10.23. Routes for the Microposts resource.
config/routes.rb
SampleApp::Application.routes.draw do
resources :users
resources :sessions,   only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
.
.
.
end

HTTP requestURIActionPurpose
POST/micropostscreatecreate a new micropost
DELETE/microposts/1destroydelete micropost with id 1
Table 10.2: RESTful routes provided by the Microposts resource in Listing 10.23.

10.3.1 Access control

We begin our development of the Microposts resource with some access control in the Microposts controller. The idea is simple: both the create and destroy actions should require users to be signed in. The RSpec code to test for this appears in Listing 10.24. (We’ll test for and add a third protection—ensuring that only a micropost’s user can destroy it—in Section 10.3.4.)

Listing 10.24. Access control tests for microposts.
spec/requests/authentication_pages_spec.rb
require 'spec_helper'

describe "Authentication" do
.
.
.
describe "authorization" do

describe "for non-signed-in users" do
let(:user) { FactoryGirl.create(:user) }
.
.
.
describe "in the Microposts controller" do

describe "submitting to the create action" do
before { post microposts_path }
specify { response.should redirect_to(signin_path) }
end

describe "submitting to the destroy action" do
before do
micropost = FactoryGirl.create(:micropost)
delete micropost_path(micropost)
end
specify { response.should redirect_to(signin_path) }
end
end
.
.
.
end
end
end
end


Rather than using the (yet-to-be-built) web interface for microposts, the code in Listing 10.24 operates at the level of the individual micropost actions, a strategy we first saw in Listing 9.14. In this case, a non-signed-in user is redirected upon submitting a POST request to /microposts (post microposts_path, which hits the create action) or submitting a DELETE request to /microposts/1 (delete micropost_path(micropost), which hits the destroy action).

Writing the application code needed to get the tests in Listing 10.24 to pass requires a little refactoring first. Recall from Section 9.2.1 that we enforced the signin requirement using a before filter that called the signed_in_user method (Listing 9.12). At the time, we only needed that method in the Users controller, but now we find that we need it in the Microposts controller as well, so we’ll move it into the Sessions helper, as shown in Listing 10.25.9

Listing 10.25. Moving the signed_in_user method into the Sessions helper.
app/helpers/sessions_helper.rb
module SessionsHelper
.
.
.
def current_user?(user)
user == current_user
end

def signed_in_user
unless signed_in?
store_location
end
end
.
.
.
end


To avoid code repetition, you should also remove signed_in_user from the Users controller at this time.

With the code in Listing 10.25, the authenticate method is now available in the Microposts controller, which means that we can restrict access to the create and destroy actions with the before filter shown in Listing 10.26. (Since we didn’t generate it at the command line, you will have to create the Microposts controller file by hand.)

Listing 10.26. Adding authentication to the Microposts controller actions.
app/controllers/microposts_controller.rb
class MicropostsController < ApplicationController
before_filter :signed_in_user

def create
end

def destroy
end
end


Note that we haven’t restricted the actions the before filter applies to since it applies to them both by default. If we were to add, say, an index action accessible even to non-signed-in users, we would need to specify the protected actions explicitly:

class MicropostsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]

def index
end

def create
end

def destroy
end
end


At this point, the tests should pass:

$bundle exec rspec spec/requests/authentication_pages_spec.rb  10.3.2 Creating microposts In Chapter 7, we implemented user signup by making an HTML form that issued an HTTP POST request to the create action in the Users controller. The implementation of micropost creation is similar; the main difference is that, rather than using a separate page at /microposts/new, we will (following Twitter’s convention) put the form on the Home page itself (i.e., the root path /), as mocked up in Figure 10.9. When we last left the Home page, it appeared as in Figure 5.7—that is, it had a big, fat “Sign up now!” button in the middle. Since a micropost creation form only makes sense in the context of a particular signed-in user, one goal of this section will be to serve different versions of the Home page depending on a visitor’s signin status. We’ll implement this in Listing 10.29 below, but we can still write the test now. As with the Users resource, we’ll use an integration test: $ rails generate integration_test micropost_pages


The micropost creation tests then parallel those for user creation from Listing 7.15; the result appears in Listing 10.27.

Listing 10.27. Tests for creating microposts.
spec/requests/micropost_pages_spec.rb
require 'spec_helper'

describe "Micropost pages" do

subject { page }

let(:user) { FactoryGirl.create(:user) }
before { sign_in user }

describe "micropost creation" do
before { visit root_path }

describe "with invalid information" do

it "should not create a micropost" do
expect { click_button "Submit" }.should_not change(Micropost, :count)
end

describe "error messages" do
let(:error) { '1 error prohibited this micropost from being saved' }
before { click_button "Submit" }
it { should have_content(error) }
end
end

describe "with valid information" do

before { fill_in 'micropost_content', with: "Lorem ipsum" }
it "should create a micropost" do
expect { click_button "Submit" }.should change(Micropost, :count).by(1)
end
end
end
end


We’ll start with the create action for microposts, which is similar to its user analogue (Listing 7.24); the principal difference lies in using the user/micropost association to build the new micropost, as seen in Listing 10.28.

Listing 10.28. The Microposts controller create action.
app/controllers/microposts_controller.rb
class MicropostsController < ApplicationController
before_filter :signed_in_user

def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_path
else
render 'static_pages/home'
end
end

def destroy
end
end


To build a form for creating microposts, we use the code in Listing 10.29, which serves up different HTML based on whether the site visitor is signed in or not.

app/views/static_pages/home.html.erb
<% provide(:title, 'Home') %>
<% if signed_in? %>
<table class="front">
<tr>
<td class="main">
<h1 class="micropost">What's up?</h1>
<%= render 'shared/micropost_form' %>
</td>
<td class="sidebar round">
<%= render 'shared/user_info' %>
</td>
</tr>
</table>
<% else %>
<h1>Sample App</h1>

<p>
<a href="http://railstutorial.org/">Ruby on Rails Tutorial</a>
sample application.
</p>

<% end %>


Having so much code in each branch of the if-else conditional is a bit messy, and cleaning it up using partials is left as an exercise (Section 10.5). Filling in the necessary partials from Listing 10.29 isn’t an exercise, though; we fill in the new Home page sidebar in Listing 10.30 and the micropost form partial in Listing 10.31.

Listing 10.30. The partial for the user info sidebar.
app/views/shared/_user_info.html.erb
<div class="user_info">
<a href="<%= user_path(current_user) %>">
<%= gravatar_for(current_user, size: 30) %>
<span class="user_name">
<%= current_user.name %>
</span>
<span class="microposts">
<%= pluralize(current_user.microposts.count, "micropost") %>
</span>
</a>
</div>


As in Listing 9.25, the code in Listing 10.30 uses the version of the gravatar_for helper defined in Listing 7.28.

Note that, as in the profile sidebar (Listing 10.18), the user info in Listing 10.30 displays the total number of microposts for the user. There’s a slight difference in the display, though; in the profile sidebar, Microposts is a label, and showing Microposts 1 makes perfect sense. In the present case, though, saying “1 microposts” is ungrammatical, so we arrange to display “1 micropost” (but “2 microposts”) using the convenient pluralize helper method.

We next define the form for creating microposts (Listing 10.31), which is analogous to the signup form in Listing 7.16.

Listing 10.31. The form partial for creating microposts.
app/views/shared/_micropost_form.html.erb
<%= form_for(@micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>


We need to make two changes before the form in Listing 10.31 will work. First, we need to define @micropost, which (as before) we do through the association:

@micropost = current_user.microposts.build


The result appears in Listing 10.32.

Listing 10.32. Adding a micropost instance variable to the home action.
app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController

def home
@micropost = current_user.microposts.build if signed_in?
end
.
.
.
end


Since the micropost is not yet associated with a user, Micropost.new would work in this context as well, but the code in Listing 10.32 has the advantage that it will break the test suite if we forget to require the user to sign in.

The second change needed to get Listing 10.31 to work is to redefine the error messages partial so that

<%= render 'shared/error_messages', object: f.object %>


works. You may recall from Listing 7.21 that the error messages partial references the @user variable explicitly, but in the present case we have an @micropost variable instead. We should define an error messages partial that works regardless of the kind of object passed to it. Happily, the form variable f can access the associated object through f.object, so that in

form_for(@user) do |f|


f.object is @user, and in

form_for(@micropost) do |f|


f.object is @micropost.

To pass the object to the partial, we use a hash with value equal to the object and key equal to the desired name of the variable in the partial, which is what this code accomplishes:

<%= render 'shared/error_messages', object: f.object %>


In other words, object: f.object creates a variable called object in the error_messages partial. We can use this object to construct a customized error message using a fancy chain of Rails methods, as shown in Listing 10.33.

Listing 10.33. Updating the error-messages partial from Listing 7.22 to work with other objects.
app/views/shared/_error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(object.errors.count, "error") %>
prohibited this <%= object.class.to_s.underscore.humanize.downcase %>
from being saved:</h2>
<p>There were problems with the following fields:</p>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>


If you want to become more familiar with the text-manipulation methods in Listing 10.33, the Rails console is a useful tool:

$rails console >> Micropost.new.class.to_s.underscore.humanize => "micropost"  Note that the underscore method does nothing in the present case but is required to support classes with compound names: >> "NewsReport".underscore => "news_report" >> "NewsReport".underscore.humanize => "News report"  See the Rails API entry on ActiveSupport::Inflector for more on these sorts of utilities. As this point, the tests in Listing 10.27 should be passing: $ bundle exec rspec spec/requests/micropost_pages_spec.rb


Unfortunately, the User request spec is now broken because the signup and edit forms use the old version of the error messages partial. To fix them, we’ll update them with the more general version, as shown in Listing 10.34 and Listing 10.35. (Note: Your code will differ if you implemented Listing 9.50 and Listing 9.51 from the exercises in Section 9.6. Mutatis mutandis.)

Listing 10.34. Updating the rendering of user signup errors.
app/views/users/new.html.erb
<% provide(:title, 'Sign up') %>

<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
.
.
.
<% end %>

Listing 10.35. Updating the errors for editing users.
app/views/users/edit.html.erb
<% provide :title, "Edit user" %>
<h1>Edit user</h1>

<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
.
.
.
<% end %>

<div>
<%= gravatar_for(@user) %>
<a href="http://gravatar.com/emails">change</a>
</div>


At this point, all the tests should be passing:

$bundle exec rspec spec/  Additionally, all the HTML in this section should render properly, showing the form as in Figure 10.10, and a form with a submission error as in Figure 10.11. You are invited at this point to create a new post for yourself and verify that everything is working—but you should probably wait until after Section 10.3.3. 10.3.3 A proto-feed The comment at the end of Section 10.3.2 alluded to a problem: the current Home page doesn’t display any microposts. If you like, you can verify that the form shown in Figure 10.10 is working by submitting a valid entry and then navigating to the profile page to see the post, but that’s rather cumbersome. It would be far better to have a feed of microposts that includes the user’s own posts, as mocked up in Figure 10.12. (In Chapter 11, we’ll generalize this feed to include the microposts of users being followed by the current user.) Since each user should have a feed, we are led naturally to a feed method in the User model. Eventually, we will test that the feed returns the microposts of the users being followed, but for now we’ll just test that the feed method includes the current user’s microposts but excludes the posts of a different user. We can express these requirements in code with Listing 10.36. Listing 10.36. Tests for the (proto-)status feed. spec/models/user_spec.rb require 'spec_helper' describe User do . . . it { should respond_to(:microposts) } it { should respond_to(:feed) } . . . describe "micropost associations" do before { @user.save } let!(:older_micropost) do FactoryGirl.create(:micropost, user: @user, created_at: 1.day.ago) end let!(:newer_micropost) do FactoryGirl.create(:micropost, user: @user, created_at: 1.hour.ago) end . . . describe "status" do let(:unfollowed_post) do FactoryGirl.create(:micropost, user: FactoryGirl.create(:user)) end its(:feed) { should include(newer_micropost) } its(:feed) { should include(older_micropost) } its(:feed) { should_not include(unfollowed_post) } end end end  These tests introduce (via the RSpec boolean convention) the array include? method, which simply checks if an array includes the given element:10 $ rails console
>> a = [1, "foo", :bar]
>> a.include?("foo")
=> true
>> a.include?(:bar)
=> true
>> a.include?("baz")
=> false


This example shows just how flexible the RSpec boolean convention is; even though include is already a Ruby keyword (used to include a module, as seen in, e.g., Listing 8.14), in this context RSpec correctly guesses that we want to test array inclusion.

We can arrange for an appropriate micropost feed method by selecting all the microposts with user_id equal to the current user’s id, which we accomplish using the where method on the Micropost model, as shown in Listing 10.37.11

Listing 10.37. A preliminary implementation for the micropost status feed.
app/models/user.rb
class User < ActiveRecord::Base
.
.
.
def feed
# This is preliminary. See "Following users" for the full implementation.
Micropost.where("user_id = ?", id)
end
.
.
.
end


The question mark in

Micropost.where("user_id = ?", id)


ensures that id is properly escaped before being included in the underlying SQL query, thereby avoiding a serious security hole called SQL injection. The id attribute here is just an integer, so there is no danger in this case, but always escaping variables injected into SQL statements is a good habit to cultivate.

Alert readers might note at this point that the code in Listing 10.37 is essentially equivalent to writing

def feed
microposts
end


We’ve used the code in Listing 10.37 instead because it generalizes much more naturally to the full status feed needed in Chapter 11.

To test the display of the status feed, we first create a couple of microposts and then verify that a table row (tr) appears on the page for each one (Listing 10.38).

Listing 10.38. A test for rendering the feed on the Home page.
spec/requests/static_pages_spec.rb
require 'spec_helper'

describe "Static pages" do

subject { page }

.
.
.
describe "for signed-in users" do
let(:user) { FactoryGirl.create(:user) }
before do
FactoryGirl.create(:micropost, user: user, content: "Lorem ipsum")
FactoryGirl.create(:micropost, user: user, content: "Dolor sit amet")
sign_in user
visit root_path
end

it "should render the user's feed" do
user.feed.each do |item|
page.should have_selector("tr##{item.id}", text: item.content)
end
end
end
end
.
.
.
end


Listing 10.38 assumes that each feed item has a unique CSS id, so that

page.should have_selector("tr##{item.id}", text: item.content)


will generate a match for each item. (Note that the first # in tr##{item.id} is Capybara syntax for a CSS id, whereas the second # is the beginning of a Ruby string interpolation #{}.)

To use the feed in the sample application, we add an @feed_items instance variable for the current user’s (paginated) feed, as in Listing 10.39, and then add a feed partial (Listing 10.40) to the Home page (Listing 10.42). (Adding tests for pagination is left as an exercise; see Section 10.5.)

Listing 10.39. Adding a feed instance variable to the home action.
app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController

def home
if signed_in?
@micropost  = current_user.microposts.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
.
.
.
end

Listing 10.40. The status feed partial.
app/views/shared/_feed.html.erb
<% if @feed_items.any? %>
<table class="microposts">
<%= render partial: 'shared/feed_item', collection: @feed_items %>
</table>
<%= will_paginate @feed_items %>
<% end %>


The status feed partial defers the feed item rendering to a feed item partial using the code

<%= render partial: 'shared/feed_item', collection: @feed_items %>


Here we pass a :collection parameter with the feed items, which causes render to use the given partial (’feed_item’ in this case) to render each item in the collection. (We have omitted the :partial parameter in previous renderings, writing, e.g., render ’shared/micropost’, but with a :collection parameter that syntax doesn’t work.) The feed item partial itself appears in Listing 10.41.

Listing 10.41. A partial for a single feed item.
app/views/shared/_feed_item.html.erb
<tr id="<%= feed_item.id %>">
<td class="gravatar">
</td>
<td class="micropost">
<span class="user">
</span>
<span class="content"><%= feed_item.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
</span>
</td>
</tr>


Listing 10.41 also adds a CSS id for each feed item using

<tr id="<%= feed_item.id %>">


as required by the test in Listing 10.38.

We can then add the feed to the Home page by rendering the feed partial as usual (Listing 10.42). The result is a display of the feed on the Home page, as required (Figure 10.13).

app/views/static_pages/home.html.erb
<% provide(:title, 'Home') %>
<% if signed_in? %>
<table class="front">
<tr>
<td class="main">
<h1 class="micropost">What's up?</h1>
<%= render 'shared/micropost_form' %>
<%= render 'shared/feed' %>
</td>
.
.
.
</tr>
</table>

<% else %>
.
.
.
<% end %>


At this point, creating a new micropost works as expected, as seen in Figure 10.14. There is one subtlety, though: on failed micropost submission, the Home page expects an @feed_items instance variable, so failed submissions currently break (as you should be able to verify by running your test suite). The easiest solution is to suppress the feed entirely by assigning it an empty array, as shown in Listing 10.43.12

Listing 10.43. Adding an (empty) @feed_items instance variable to the create action.
app/controllers/microposts_controller.rb
class MicropostsController < ApplicationController
.
.
.
def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_path
else
@feed_items = []
render 'static_pages/home'
end
end
.
.
.
end


At this point, the proto-feed should be working, and the test suite should pass:



10.4 Conclusion

With the addition of the Microposts resource, we are nearly finished with our sample application. All that remains is to add a social layer by letting users follow each other. We’ll learn how to model such user relationships, and see the implications for the status feed, in Chapter 11.

Before proceeding, be sure to commit and merge your changes if you’re using Git for version control:

$git add .$ git commit -m "Add user microposts"
$git checkout master$ git merge user-microposts
$git push  You can also push the app up to Heroku at this point. Because the data model has changed through the addition of the microposts table, you will also need to migrate the production database: $ git push heroku
$heroku run rake db:migrate$ heroku run rake db:populate


10.5 Exercises

We’ve covered enough material now that there is a combinatorial explosion of possible extensions to the application. Below are just a few of the many possibilities.

1. Add tests for the sidebar micropost counts (including proper pluralization).
2. Add tests for micropost pagination.
3. Refactor the Home page to use separate partials for the two branches of the if-else statement.
4. Write a test to make sure delete links do not appear for microposts not created by the current user.
5. Using partials, eliminate the duplication in the delete links from Listing 10.44 and Listing 10.45.
6. Very long words currently break our layout, as shown in Figure 10.17. Fix this problem using the wrap helper defined in Listing 10.48. Note the use of the raw method to prevent Rails from escaping the resulting HTML, together with the sanitize method needed to prevent cross-site scripting. This code also uses the strange-looking but useful ternary operator (Box 10.1).
7. (mainly for designers) Modify the microposts listing to use an ordered list instead of a table. Then add the appropriate CSS to make the resulting feed not look like crap.
Listing 10.48. A helper to wrap long words.
app/helpers/microposts_helper.rb
module MicropostsHelper

def wrap(content)
sanitize(raw(content.split.map{ |s| wrap_long_string(s) }.join(' ')))
end

private

def wrap_long_string(text, max_width = 30)
zero_width_space = "&#8203;"
regex = /.{1,#{max_width}}/
(text.length < max_width) ? text :
text.scan(regex).join(zero_width_space)
end
end

1. Technically, we treated sessions as a resource in Chapter 8, but sessions are not saved to the database the way users and microposts are.
2. The content attribute will be a string, but, as noted briefly in Section 2.1.2, for longer text fields you should use the text data type.
3. In the sense of semantic markup, it would probably be better to use an ordered list, but in that case the vertical alignment of text and images is much more difficult than with tables. See the exercise in Section 10.5 if you insist on struggling with the semantic version.
4. For convenience, Listing 10.21 actually has all the CSS needed for this chapter.
5. (i.e., the five users with custom Gravatars, and one with the default Gravatar)
6. Tail your log/development.log file if you’re curious about the SQL this method generates.
7. By design, the Faker gem’s lorem ipsum text is randomized, so the contents of your sample microposts will differ.
8. The other two resources are Users in Section 7.2 and Sessions in Section 8.1
9. We noted in Section 8.2.1 that helper methods are available only in views by default, but we arranged for the Sessions helper methods to be available in the controllers as well by adding include SessionsHelper to the Application controller (Listing 8.14).
10. Learning about methods such as include? is one reason why, as noted in Section 1.1.1, I recommend reading a pure Ruby book after finishing this one.
11. See the Rails Guide on the Active Record Query Interface for more on where and the like.
12. Unfortunately, returning a paginated feed doesn’t work in this case. Implement it and click on a pagination link to see why.
Michael Hartl is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com.