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.

546<br />

appendix B<br />

Tidbits<br />

This appendix contains a collection of tidbits that we just couldn’t fit into the rest<br />

of the book. They are designed to be read by themselves, although you are welcome<br />

(and encouraged!) to read as many of them at once as you wish.<br />

B.1 Prettying URLs<br />

In your application you’ve got a URL such as /projects/1/tickets/2, which really<br />

isn’t that pretty. Let’s take a look at how you can make the ticket’s ID part of these<br />

URLs a little prettier, turning them into something like /projects/1/tickets/2-makeit-shiny.<br />

Having URLs such as /projects/1/tickets/2-make-it-shiny will allow your users to<br />

easily identify what that URL links to without having to visit the page. 1 Rails allows<br />

you to very easily do this by overriding a method called to_param in the model<br />

where you want to have pretty URLs. This method is defined like this within<br />

ActiveRecord::Base, and so all your models inherit it:<br />

def to_param<br />

id<br />

end<br />

This method is used to construct the URLs generated by the link helpers in your<br />

application such as project_ticket_path, if you use them like this:<br />

project_ticket_path(project, ticket)<br />

Rails does not care what the classes of the objects that are passed in here are; it just<br />

assumes you know what you’re doing. What it does care about though is the output<br />

of the to_param method, which must not contain any slashes. To get the pretty URL<br />

you always wanted you can use the parameterize method on any String, which<br />

works like this:<br />

"Make it shiny!".parameterize<br />

= "make-it-shiny"<br />

It does this by substituting any character that isn’t a through z, the digits 0 through<br />

9, a hyphen (-), or an underscore (_) into the - character. If the string ends in one<br />

1 It’s also supposedly good for search engine optimization (SEO).

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

Saved successfully!

Ooh no, something went wrong!