27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

130 CHAPTER 6 Authentication and basic authorization<br />

intelligently uses the name of the belongs_to association to imply that the fields are<br />

project_id and user_id, respectively. When looking up a user, Active Record performs<br />

a query like this:<br />

SELECT * FROM users WHERE id = #{@ticket.user_id}<br />

This query then returns a row from the database that matches the ID (if there is one),<br />

and Active Record creates a new User object from this result.<br />

With these associations set up, you now need to add a field on the tickets table to<br />

store the ID of the user that a ticket links to. Run this command:<br />

rails g migration add_user_id_to_tickets user_id:integer<br />

Based solely on how you wrote the name of this feature, Rails will understand that you<br />

want to add a particular column to the tickets table. You specify the name and type<br />

of the column after the migration name, and Rails creates the migration with the field<br />

prefilled for you.<br />

If you open the new migration file (it’s the last one in the db/migrate directory),<br />

you’ll see the output in the following listing.<br />

Listing 6.9 db/migrate/[timestamp]_add_user_id_to_tickets.rb<br />

class AddUserIdToTickets < ActiveRecord::Migration<br />

def change<br />

add_column :tickets, :user_id, :integer<br />

end<br />

end<br />

It’s all done for you! You can close this file and then run the migration with rake<br />

db:migrate and prepare the test database by using rake db:test:prepare.<br />

Let’s rerun bin/cucumber features/creating_tickets.feature and see where it<br />

stands now:<br />

Then I should see "Created by user@ticketee.com"<br />

expected there to be content "Created by user@ticketee.com" in "[text]"<br />

Bash migrate alias<br />

If you’re using bash as a shell (which is probably the case if you’re on a UNIX operating<br />

system), you could add an alias to your ~/.bashrc to do both of these steps<br />

for you rather than having to type them out:<br />

alias migrate='rake db:migrate && rake db:test:prepare'<br />

Then type source ~/.bashrc, and the alias will be available to you in your current<br />

terminal window. It’ll also be available in new terminal windows even if you didn’t use<br />

source, because this file is processed every time a new bash session is started. If<br />

you don’t like typing source, then . ~/.bashrc will do.

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

Saved successfully!

Ooh no, something went wrong!