<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>Travis on Rails</title>
    <description>Recent Posts</description>
    <link>http://www.travisonrails.com/feed/posts.rss</link>
    <item>
      <title>Working with the flash hash</title>
      <description>&lt;p&gt;The &lt;kbd&gt;flash&lt;/kbd&gt; hash is what Rails uses to display messages (both notices and errors).  Since it's a Hash, you can assign any key/value pair that you want, but I tend to stick with &lt;kbd&gt;flash[:notice]&lt;/kbd&gt; for a success message, and &lt;kbd&gt;flash[:error]&lt;/kbd&gt; for an error message.&lt;/p&gt;

&lt;p&gt;In my opinion, using the &lt;kbd&gt;flash&lt;/kbd&gt; hash is a little confusing.  I haven't come across a book or tutorial that fully explains how to control it properly.  So, here are the options for using the &lt;kbd&gt;flash&lt;/kbd&gt; hash in Rails.&lt;/p&gt;

&lt;h4&gt;flash[:key] and flash.now[:key]&lt;/h4&gt;

&lt;p&gt;The following method shows how to best use the &lt;kbd&gt;flash&lt;/kbd&gt; hash:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;def create
  @user = User.new(params[:user])
  respond_to do |format|
    if @user.save
      flash[:notice] = 'User was successfully created.'
      format.html { redirect_to admin_users_path }
    else
      flash.now[:error] = 'The user could not be created'
      format.html { render :action =&gt; 'new' }
    end
  end
rescue Exception =&gt; ex
  logger.warn('ERROR: ' + ex.message)
  flash.now[:error] = 'There was an error creating the user.'
  render :action =&gt; 'new'
end&lt;/pre&gt;

&lt;p&gt;Notice that I use the &lt;kbd&gt;flash&lt;/kbd&gt; hash in two different ways: &lt;kbd&gt;flash[:key]&lt;/kbd&gt; and &lt;kbd&gt;flash.now[:key]&lt;/kbd&gt;. The way I use it depends on when I want it displayed. The &lt;kbd&gt;flash[:key]&lt;/kbd&gt; usage should &lt;strong&gt;only&lt;/strong&gt; be used before redirection, because it makes the object available for the current action &lt;em&gt;and&lt;/em&gt; the next action. The &lt;kbd&gt;flash.now[:key]&lt;/kbd&gt; usage should be used when you only want the &lt;kbd&gt;flash&lt;/kbd&gt; object to be available to the current action.&lt;/p&gt;

&lt;p&gt;Here's an example why you shouldn't use &lt;kbd&gt;flash[:key]&lt;/kbd&gt; without redirection.  Let's say this is your controller:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;class MainController &amp;lt; ApplicationController
  def index
    flash[:notice] = 'Welcome to the site!'
  end
  
  def profile
  end
end&lt;/pre&gt;

&lt;p&gt;When you visit the index page, you'll see the message 'Welcome to the site!.' If you then click a link from the index page that takes you to the profile page, you'll still see the message 'Welcome to the site!' because the &lt;kbd&gt;flash[:key]&lt;/kbd&gt; is available to the current action &lt;em&gt;and&lt;/em&gt; the next action.&lt;/p&gt;

&lt;h4&gt;Displaying the flash&lt;/h4&gt;

&lt;p&gt;Here is a really helpful method to display the contents of the &lt;kbd&gt;flash&lt;/kbd&gt; hash that I modified from one of Ryan Bates' awesome &lt;a href="http://railscasts.com/episodes/18-looping-through-flash"&gt;Railscasts&lt;/a&gt;:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;&amp;lt;%- flash.each do |key, msg| -%&amp;gt;
	&amp;lt;div id=&amp;quot;&amp;lt;%= key %&amp;gt;&amp;quot;&amp;gt;
		&amp;lt;p style=&amp;quot;float:right;&amp;quot;&amp;gt;&amp;lt;%= link_to_function &amp;#x27;X&amp;#x27;, &amp;quot;Effect.Fade(&amp;#x27;#{key}&amp;#x27;)&amp;quot; %&amp;gt;&amp;lt;/p&amp;gt;
		&amp;lt;p&amp;gt;&amp;lt;%= msg %&amp;gt;&amp;lt;/p&amp;gt;
		&amp;lt;div class=&amp;quot;clear&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
	&amp;lt;/div&amp;gt;
&amp;lt;%- end -%&amp;gt;&lt;/pre&gt;

&lt;p&gt;This method will loop through each key in your &lt;kbd&gt;flash&lt;/kbd&gt; hash and create a div with the name of the key, then put the contents inside with a link to close the message div.&lt;/p&gt;

&lt;p&gt;I put this method in a partial called &lt;kbd&gt;_notice_div.html.erb&lt;/kbd&gt; and include it at the top of my application layout.  Here are the styles I use for notices and errors:&lt;/p&gt;

&lt;pre name="code" class="css"&gt;#notice { background-color: #A4E7A0; border: 1px solid #26722D; }
#error { background-color: #F0A8A8; border: 1px solid #900; }
#notice, #error { width: 90%; margin: 0 auto 10px auto; padding: 5px; }
#notice p, #error p { margin-left: 20px; padding: 0; font-size: .75em; color: #000; }
#notice a, #error a { text-decoration: none; padding: 0 3px; }
#notice a { border: 1px solid #26722D; color: #26722D; }
#error a { border: 1px solid #900; color: #900; }
#notice a:hover, #error a:hover { color: #333; border: 1px solid #333; }&lt;/pre&gt;

&lt;div id="notice"&gt;
	&lt;p&gt;This is a notice div.&lt;/p&gt;
&lt;/div&gt;

&lt;div id="error"&gt;
	&lt;p&gt;This is an error div.&lt;/p&gt;
&lt;/div&gt;</description>
      <pubDate>Sun, 17 Aug 2008 00:00:00 -0400</pubDate>
      <link>http://www.travisonrails.com/2008/08/17/Working-with-the-flash-hash</link>
    </item>
    <item>
      <title>Routes Demystified</title>
      <description>&lt;p&gt;It took me a while to discover the full potential of Rails' routes.  I slowly learned more and more neat stuff that made me like them more and more. They are extremely powerful and are very useful for URL re-writing. Following is all of my route knowledge. If you notice something that I didn't cover, please leave it in the comments.&lt;/p&gt;

&lt;p&gt;A few basic routes:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;# this will route domain.com/ to the index action of your main controller
map.connect '', :controller =&gt; 'main'

# this will create a custom URL for your about-us page
map.connect 'custom-url/about-us', :controller =&gt; 'about_us', :action =&gt; 'index'&lt;/pre&gt;

&lt;p&gt;Pay attention to the order of your routes in your &lt;kbd&gt;routes.rb&lt;/kbd&gt; file. They are evaluated in order from top to bottom. Routes at the top will be used before routes at the bottom if they are too similar.&lt;/p&gt;

&lt;h4&gt;Named Routes&lt;/h4&gt;

&lt;p&gt;Instead of saying &lt;kbd&gt;map.connect&lt;/kbd&gt;, let's get crazy and name our routes. I'll use the same routes as above and add a few.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;# you can now call this route with home_path or home_url
map.home '', :controller =&gt; 'main'

# call this route with about_us_path or about_us_url
map.about_us 'custom-url/about-us', :controller =&gt; 'about_us', :action =&gt; 'index'

# symbols in the routes define options you pass when calling the route
# call product_details_path(:id =&gt; @product) to access this route
map.product_details 'products/detail-view/:id', :controller =&gt; 'products', :action =&gt; 'show'
# all-purpose route for the products controller : products_path(:action =&gt; 'search') or products_path(:action =&gt; 'buy', :id =&gt; product)
map.products 'products/:action/:id', :controller =&gt; 'products'&lt;/pre&gt;

&lt;h4&gt;Route Blocks Using with_options&lt;/h4&gt;

&lt;p&gt;If we have several routes for the same controller, it makes sense to use &lt;kbd&gt;with_options&lt;/kbd&gt; to simplify the definitions.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;map.with_options :controller =&gt; 'news' do |m|
  m.news 'news-releases/list', :action =&gt; 'index' # news_path
  m.news_details 'news-releases/details/:id', :action =&gt; 'show' # news_details_path(:id =&gt; news_release)
  m.news_author 'news-releases/by-author/:name', :action =&gt; 'author' # news_author_path(:name =&gt; 'Bill')
end&lt;/pre&gt;

&lt;h4&gt;Better URLs with Routes&lt;/h4&gt;

&lt;p&gt;Routes are great for creating search engine friendly URLs. Supposed you'd like to add the title of your blog post to the URL.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;map.blog_details 'blog/details/:id/:name', :controller =&gt; 'blog', :action =&gt; 'show', :name =&gt; nil&lt;/pre&gt;

&lt;p&gt;Now you can call the &lt;kbd&gt;blog_details&lt;/kbd&gt; path and give it the &lt;kbd&gt;:id&lt;/kbd&gt; and &lt;kbd&gt;:title&lt;/kbd&gt; as options for the URL. Also notice that I set &lt;kbd&gt;:name =&gt; nil&lt;/kbd&gt; at the end of the route. This marks that option as optional for the route call.&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;# this call will generate the following URL: http://domain.com/blog/details/1/My-First-Blog-Post
# I'm using a helper method in this call entitled 'strip_chars', it is below
blog_details_path(:id =&gt; post, :title =&gt; strip_chars(post.title)) %&gt;

# you can also omit the title when invoking the route because it is optional.
# since your 'details' method will be using the :id parameter to find the record
# we don't really need the title, it's just for search engines
blog_details_path(:id =&gt; post) %&gt;

# this helper method takes a string, replaces all spaces with dashes, then strips out all non-letter, non-number, non-dashes
# it's good for generating URL-friendly titles
def strip_chars(string='')
  return '' if string.blank?
  string.gsub(' ','-').gsub(/[^a-z0-9\-]+/i, '')
end&lt;/pre&gt;

&lt;h4&gt;Caching and Pagination&lt;/h4&gt;

&lt;p&gt;If we cache our site, and certain actions show a paginated list, then we need to add the &lt;kbd&gt;:page&lt;/kbd&gt; attribute to the route to ensure that the cache is recorded properly. After all, to our server &lt;kbd&gt;/blog/list&lt;/kbd&gt; looks the exact same as &lt;kbd&gt;/blog/list?page=2&lt;/kbd&gt; when retrieving cached pages.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;map.blog 'blog/list/:page',
         :controller =&gt; 'blog',
         :action =&gt; 'list',
         :requirements =&gt; {:page =&gt; /\d+/},
         :page =&gt; nil
# blog_path
# blog_path(:page =&gt; 1)&lt;/pre&gt;

&lt;p&gt;Notice that we added something new, the &lt;kbd&gt;:requirements&lt;/kbd&gt; option. For &lt;kbd&gt;:page&lt;/kbd&gt;, it's a regular expression telling us the supplied value must be a number. I've also set &lt;kbd&gt;:page =&gt; nil&lt;/kbd&gt; so that we don't always have to specify it when invoking the route.&lt;/p&gt;

&lt;p&gt;One thing to watch out for when calling a paged route is to be careful when you're on another paged section of your site. Say I have the route above for blogs and a similar route for news releases. If I'm on the page &lt;kbd&gt;/news/list/5&lt;/kbd&gt; and I call &lt;kbd&gt;blog_path&lt;/kbd&gt; it will take the &lt;kbd&gt;:page&lt;/kbd&gt; parameter from the current URL and you'll end up on page 5 of your blog post list. Confused? Just make sure when you are calling a paged route to specify it as &lt;kbd&gt;blog_path(:page =&gt; 1)&lt;/kbd&gt; to explicitly go to &lt;kbd&gt;/blog/list/1&lt;/kbd&gt; or call &lt;kbd&gt;blog_path(:page =&gt; nil)&lt;/kbd&gt; to go to &lt;kbd&gt;/blog/list&lt;/kbd&gt;. Both will work.&lt;/p&gt;

&lt;h4&gt;Route Conditions&lt;/h4&gt;

&lt;p&gt;Similar to RESTful routes, you can specify the method of the request with the &lt;kbd&gt;:requirements&lt;/kbd&gt; option. While this is useful, it makes much more sense to just use &lt;kbd&gt;map.resources&lt;/kbd&gt; to get &lt;em&gt;real&lt;/em&gt; RESTful routes.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;map.connect 'blog-post/:id', :controller =&gt; 'blog', :action =&gt; 'show', :requirements =&gt; { :method =&gt; :get }
map.connect 'blog-post/:id', :controller =&gt; 'blog', :action =&gt; 'update', :requirements =&gt; { :method =&gt; :post }

# a GET method to /blog-post/1 will route to the 'show' action
# a POST method to /blog-post/1 will route to the 'update' action&lt;/pre&gt;

&lt;p&gt;I think that's enough for normal routes. Hopefully soon I can write a post on RESTful routes, which are a whole different beast.&lt;/p&gt;</description>
      <pubDate>Sat, 02 Aug 2008 00:00:00 -0400</pubDate>
      <link>http://www.travisonrails.com/2008/08/02/Routes-Demystified</link>
    </item>
    <item>
      <title>Rails Tips</title>
      <description>&lt;p&gt;While there are no shortages of posts listing tips for Rails, or lesser-known Ruby methods, I decided to write this post because these are shortcuts or helpers that I didn't know about until fairly recently.  I'm going to try and update this post as I discover new &lt;em&gt;railties&lt;/em&gt; and &lt;em&gt;rubyisms&lt;/em&gt; along the way, so check back every now and then.&lt;/p&gt;

&lt;br /&gt;

&lt;h4 style="margin:0; padding-bottom:5px;"&gt;Symbol#to_proc&lt;/h4&gt;

&lt;p&gt;This is really a Ruby method, but it makes running a &lt;kbd&gt;collect&lt;/kbd&gt; or &lt;kbd&gt;map&lt;/kbd&gt; on ActiveRecord objects much easier.  Whereas before, you would do this:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;@members = Member.find(:all).map { |member| member.name }&lt;/pre&gt;

&lt;p&gt;Now, you can simplify it to this:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;@members = Member.find(:all).map(&amp;amp;:name)&lt;/pre&gt;

&lt;br /&gt;

&lt;h4 style="margin:0; padding-bottom:5px;"&gt;Model Calculations&lt;/h4&gt;

&lt;p&gt;This will let you do simple calculations on any ActiveRecord model (as long as the field you're calculating is numeric).&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;Student.average(:grade) # finds the average grade for all students (returns a float)
Student.maximum(:grade) # finds the highest grade
Student.minimum(:grade) # finds the lowest grade
Student.sum(:grade) # the sum of all grades&lt;/pre&gt;

&lt;br /&gt;

&lt;h4 style="margin:0; padding-bottom:5px;"&gt;Custom ActiveRecord Associations&lt;/h4&gt;

&lt;p&gt;Let's say you have a model called BlogPost and one called Comment.  A blog post has many comments, but you also have a boolean field on comments called &lt;kbd&gt;approved&lt;/kbd&gt; that signifies if it's been decided that the comment is not spam (like most comments are). This is what your BlogPost model might look like:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;class BlogPost &amp;lt; ActiveRecord::Base
  has_many :comments
end&lt;/pre&gt;

&lt;p&gt;You can add custom associations for &lt;kbd&gt;approved_comments&lt;/kbd&gt; and &lt;kbd&gt;unapproved_comments&lt;/kbd&gt; to your model to make fetching these comments a lot easier.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;class BlogPost &amp;lt; ActiveRecord::Base
  has_many :comments
  has_many :approved_comments, :class_name =&gt; 'Comment', :conditions =&gt; 'approved=1'
  has_many :unapproved_comments, :class_name =&gt; 'Comment', :conditions =&gt; 'approved=0'
end&lt;/pre&gt;

&lt;p&gt;All you have to do is specify the class name of the associated model and the conditions of the &lt;kbd&gt;find&lt;/kbd&gt;.  This makes it possible to easily access these associations from within your views.&lt;/p&gt;

&lt;p&gt;You can now show the number of approved comments for each post.&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;%= @blog_post.title %&amp;gt; - &amp;lt;%= @blog_post.approved_comments.count %&amp;gt; Comments&lt;/pre&gt;

&lt;p&gt;You can also easily list out the approved comments.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;&amp;lt;%- @blog_post.approved_comments.each do |comment| -%&amp;gt;
  &amp;lt;%= comment.author %&amp;gt; said:
  &amp;lt;%= comment.content %&amp;gt;
&amp;lt;%- end -%&amp;gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;UPDATE&lt;/strong&gt;: &lt;a href="http://codemonky.com"&gt;Shawn&lt;/a&gt; reminded me this week about &lt;kbd&gt;named_scope&lt;/kbd&gt;, which was added in Rails 2.1.  It makes custom associations a bit easier and more full-featured. You can get the same approved and non-approved comments with &lt;kbd&gt;named_scope&lt;/kbd&gt;:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;class Comment &amp;lt; ActiveRecord::Base
  belongs_to :blog_post
  named_scope :approved, :conditions =&gt; ["approved = ?", true]
  named_scope :unapproved, :conditions =&gt; ["approved = ?", false]
end&lt;/pre&gt;

&lt;p&gt;Notice that now the &lt;kbd&gt;named_scope&lt;/kbd&gt; declarations go in the &lt;kbd&gt;Comment&lt;/kbd&gt; model instead of the &lt;kbd&gt;BlogPost&lt;/kbd&gt; model like the custom associations. You get the approved comments for a post with this line:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;&amp;lt;%= blog_post.comments.approved %&amp;gt;&lt;/pre&gt;

&lt;p&gt;You can also combine &lt;kbd&gt;named_scope&lt;/kbd&gt; calls when selecting records.  Suppose our &lt;kbd&gt;Comment&lt;/kbd&gt; model now has a &lt;kbd&gt;named_scope&lt;/kbd&gt; for both approved and unapproved comments, as well as comments made by anonymous authors.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;class Comment &amp;lt; ActiveRecord::Base
  belongs_to :post
  named_scope :approved, :conditions =&gt; ["approved = ?", true]
  named_scope :unapproved, :conditions =&gt; ["approved = ?", false]
  named_scope :anonymous, :conditions =&gt; ["name = ?", 'Anonymous']
end&lt;/pre&gt;

&lt;p&gt;You can use this to find all of the approved comments for a post where the author is 'Anonymous'.&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;%= blog_post.comments.approved.anonymous %&amp;gt;&lt;/pre&gt;

&lt;p&gt;To add even more functionality to &lt;kbd&gt;named_scope&lt;/kbd&gt;, you can add conditions to the call on the fly.&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;%= post.comments.approved.all(:conditions =&gt; ["created_at &gt; ?", 2.weeks.ago]) %&amp;gt;&lt;/pre&gt;

&lt;p&gt;This will pass the additional date condition to the &lt;kbd&gt;find&lt;/kbd&gt;, making it possible to refine your searches even more.&lt;/p&gt;

&lt;br /&gt;

&lt;h4 style="margin:0; padding-bottom:5px;"&gt;Render Partial with Collection/Object&lt;/h4&gt;

&lt;p&gt;This is how I've always done my partials.&lt;/p&gt;

&lt;p&gt;The view (index.html.erb):&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;%- @posts.each do |post| -%&amp;gt;
  &amp;lt;%= render :partial =&amp;gt; 'post', :locals =&amp;gt; {:post =&amp;gt; post} %&amp;gt;
&amp;lt;%- end -%&amp;gt;&lt;/pre&gt;

&lt;p&gt;The partial (_post.html.erb):&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;%= post.title %&amp;gt; written by &amp;lt;%= post.author %&amp;gt;&lt;/pre&gt;

&lt;p&gt;I can simplify the call to the partial down to only one line of code (the partial itself will stay the same).&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;div id="all_posts"&amp;gt;
  &amp;lt;%= render :partial =&amp;gt; 'post', :collection =&amp;gt; @posts %&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;By specifying the &lt;kbd&gt;collection&lt;/kbd&gt; option, the view will call the partial &lt;kbd&gt;post&lt;/kbd&gt; for each item in the @posts array.&lt;/p&gt;

&lt;p&gt;But, let's say I wanted to call the partial for only one post.  The old way:&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;div id="single_post"&amp;gt;
  &amp;lt;%= render :partial =&amp;gt; 'post', :locals =&amp;gt; {:post =&amp;gt; @post} %&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;Not terrible, but we can make it easier with the &lt;kbd&gt;object&lt;/kbd&gt; option.&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;div id="single_post"&amp;gt;
  &amp;lt;%= render :partial =&amp;gt; 'post', :object =&amp;gt; @post %&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;This will call the partial, and pass it only the object that we specify. Shorter and cleaner.&lt;/p&gt;

&lt;br /&gt;

&lt;h4 style="margin:0; padding-bottom:5px;"&gt;RJS with link_to_function&lt;/h4&gt;

&lt;p&gt;If you have several things on your page that need to be updated, and you want to do it with a javascript call instead of an AJAX call to the server, you can do it by passing a block to the &lt;kbd&gt;link_to_function&lt;/kbd&gt; method.&lt;/p&gt;

&lt;p&gt;Suppose this is my view:&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;&amp;lt;div id="list"&amp;gt;
  &amp;lt;p id="list_title"&amp;gt;&amp;lt;%= @list.title %&amp;gt;&amp;lt;/p&amp;gt;
  &amp;lt;div id="list_items"&amp;gt;
    &amp;lt;%= render :partial =&gt; 'item', :collection =&gt; @list.items %&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;%= link_to_function 'Change it up' do |page|
    page.replace_html 'list_items', 'New Item Title'
    page.hide 'list_items'
  end %&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;This is a poor example, but hopefully you can see what I'm trying to illustrate here.&lt;/p&gt;

&lt;br /&gt;

&lt;h4 style="margin:0; padding-bottom:5px;"&gt;Simplified FIND in Rails 2.1&lt;/h4&gt;

&lt;p&gt;With the release of Rails 2.1, they've added some much-needed find methods for easily getting &lt;kbd&gt;all&lt;/kbd&gt;, &lt;kbd&gt;first&lt;/kbd&gt; and &lt;kbd&gt;last&lt;/kbd&gt; records for a model.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;@all_posts = Post.all
@first_post = Post.first
@last_post = Post.last&lt;/pre&gt;

&lt;p&gt;And, of course, you can pass &lt;kbd&gt;conditions&lt;/kbd&gt; and &lt;kbd&gt;order&lt;/kbd&gt; options to the new find methods.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;@all_posts = Post.all(:order =&gt; :updated_at)
@first_post = Post.first(:conditions =&gt; ["title LIKE ?", '%Rails%'])
@last_post = Post.last(:order =&gt; 'created_at DESC')&lt;/pre&gt;</description>
      <pubDate>Sun, 13 Jul 2008 00:00:00 -0400</pubDate>
      <link>http://www.travisonrails.com/2008/07/13/Rails-Tips</link>
    </item>
    <item>
      <title>Site Rewrite</title>
      <description>&lt;p&gt;I've been really lazy about updating the blog lately.  I'd like to say that I've been busy working on some cool new project, but the reality is that I bought a PS3 a few months ago, and all of my free time has been taken up by Call of Duty 4 and Grand Theft Auto.  By the way, if you're on PSN, send me a friend request (deadwards).&lt;/p&gt;

&lt;p&gt;To try and force myself to get back into the blog, I decided to re-write it since Rails 2.1 was &lt;a href="http://weblog.rubyonrails.com/2008/6/1/rails-2-1-time-zones-dirty-caching-gem-dependencies-caching-etc"&gt;recently released&lt;/a&gt;.  It was really funny looking at some of my old code (keep in mind, I originally wrote this blog as my first foray into Rails, circa May 06).  All of the code has at least been refactored, and in many cases totally re-written.  I've also added caching where I can to increase the speed a bit.  Hopefully, this will be the kick in the ass I need to get back to blogging.&lt;/p&gt;

&lt;p&gt;ps I finally broke down and created a &lt;a href="http://twitter.com/travisroberts"&gt;Twitter account&lt;/a&gt;.&lt;/p&gt;</description>
      <pubDate>Sun, 08 Jun 2008 00:00:00 -0400</pubDate>
      <link>http://www.travisonrails.com/2008/06/08/Site-Rewrite</link>
    </item>
    <item>
      <title>HTTP GET and POST requests with Ruby</title>
      <description>&lt;p&gt;A while ago, I was working on a project for a client that used a &lt;a href="http://campaignmonitor.com/"&gt;third-party newsletter generator&lt;/a&gt; for capturing and storing email addresses.  To add an email address, the application spits out some code for a form that you can put on your site.  A user supplies his name and email address, then submits the form and it gets stored within the third-party app's database.&lt;/p&gt;

&lt;p&gt;The problem arose when they wanted to automatically subscribe not only people who requested subscriptions, but also everyone who used the online contact form AND anyone who used the 'email to a friend' feature on one of the interior pages. Obvious misgivings aside, I set out to do what I was told (like any good drone).&lt;/p&gt;

&lt;p&gt;The problem was, I needed to do a POST request to subscribe the person to the third-party app, but I couldn't do that with a regular form because I was already posting to the actual action being invoked. Luckily, Ruby has a built in Net::HTTP class for generating GET and POST requests from within the code.&lt;/p&gt;

&lt;p&gt;Here is the method I needed to add the POST request to:&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;def email_to_friend
  ...other code...
  # now, do the dirty work
  require 'net/http'
  # get the url that we need to post to
  url = URI.parse('http://www.url.com/subscribe')
  # build the params string
  post_args1 = { 'email' =&gt; params[:email] }
  # send the request
  resp, data = Net::HTTP.post_form(url, post_args1)
end&lt;/pre&gt;

&lt;p&gt; The &lt;kbd&gt;post_form&lt;/kbd&gt; method returns a Net::HTTPResponse object and an entity body string (in Ruby 1.8, it only returns the Net::HTTPResponse object).  You can also use the &lt;kbd&gt;post&lt;/kbd&gt; method.&lt;/p&gt;

&lt;p&gt;Similarly, you can perform a GET request on a URL like so:&lt;/p&gt;

&lt;pre name="code" class="rails"&gt;require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.site.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.site.com'), '/about.html')&lt;/pre&gt;

&lt;p&gt;The &lt;kbd&gt;get&lt;/kbd&gt; method returns a String.&lt;/p&gt;

&lt;p&gt;That's simple enough, right?&lt;/p&gt;</description>
      <pubDate>Wed, 07 Nov 2007 00:00:00 -0500</pubDate>
      <link>http://www.travisonrails.com/2007/11/07/HTTP-GET-and-POST-requests-with-Ruby</link>
    </item>
    <item>
      <title>Adding multiple email attachments with Ruby on Rails</title>
      <description>&lt;p&gt;I was building some forms for a client that required the user be able to upload supporting documents along with the application.  I had implemented emailable forms before with single attachments, but never multiple.  Turns out, it was just as simple to do, I just needed to call the &lt;kbd&gt;attach&lt;/kbd&gt; function for each file I wanted to attach.&lt;/p&gt;

&lt;p&gt;Here is the method in my controller that calls the &lt;kbd&gt;ActionMailer&lt;/kbd&gt; class to send the email, where params[:file1], params[:file2], and params[:file3] are the &lt;kbd&gt;file_field_tag&lt;/kbd&gt;'s from the form:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UPDATE&lt;/strong&gt;: I've re-factored this after &lt;a href="http://codemonky.com/"&gt;Shawn&lt;/a&gt; suggested that it could be simplified into an array and iterated over.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;def submit_application
  @uploaded_files = []
  @uploaded_files &amp;lt;&amp;lt; params[:file1]
  @uploaded_files &amp;lt;&amp;lt; params[:file2]
  @uploaded_files &amp;lt;&amp;lt; params[:file3]
  ContactMailer.deliver_email_with_attachments(params[:application], @uploaded_files)
  flash[:notice] = 'Your application has been submitted.  Thank you!'
  redirect_to application_home_url
rescue Exception =&gt; ex
  logger.warn(ex.message)
  flash[:notice] = 'Uh oh!  There was an error sending your application.'
  redirect_to :back
end&lt;/pre&gt;

&lt;p&gt;And here is the &lt;kbd&gt;ActionMailer&lt;/kbd&gt; method that attaches the files.  I just need to iterate over the files, calling &lt;kbd&gt;attach&lt;/kbd&gt; for each one.&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;def email_with_attachments(application_fields={},files=[])
  @headers = {}
  @sent_on = Time.now
  @recipients = 'client@domain.com'
  @from = 'info@domain.com'

  @subject = 'Here are some file attachments'
  application_fields.keys.each {|k| @body[k] = fields[k]}

  # attach files
  files.each do |file|
    attachment "application/octet-stream" do |a|
      a.body = file.read
      a.filename = file.original_filename
    end unless file.blank?
  end
end&lt;/pre&gt;

&lt;p&gt;The &lt;kbd&gt;"application/octet-stream"&lt;/kbd&gt; is the generic MIME type for attaching unknown file types.&lt;/p&gt;

&lt;p&gt;Pretty simple!&lt;/p&gt;</description>
      <pubDate>Wed, 20 Jun 2007 00:00:00 -0400</pubDate>
      <link>http://www.travisonrails.com/2007/06/20/Adding-multiple-email-attachments-with-Ruby-on-Rails</link>
    </item>
    <item>
      <title>Parsing an RSS feed with Ruby</title>
      <description>&lt;p&gt;Parsing an RSS feed is insanely simple with Ruby.  Two lines is all it takes. . .&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;require 'rss'
rss = RSS::Parser.parse(open('http://www.travisonrails.com/feed/posts').read, false)&lt;/pre&gt;

&lt;p&gt;Now you'll have an Array of the results, so you can do something like:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;rss.items.each { |i| puts "#{i.title} - #{i.date}" }&lt;/pre&gt;</description>
      <pubDate>Sat, 09 Jun 2007 00:00:00 -0400</pubDate>
      <link>http://www.travisonrails.com/2007/06/09/Parsing-an-RSS-feed-with-Ruby</link>
    </item>
    <item>
      <title>Generate random text with Ruby</title>
      <description>&lt;p&gt;&lt;strong&gt;UPDATE&lt;/strong&gt;: Changed the &lt;kbd&gt;generate_password&lt;/kbd&gt; method slightly based on commenter Dave Burt's suggestion.&lt;/p&gt;

&lt;p&gt;I'm working on a project where the user can reset their password if they've forgotten it.  So, I need to generate a random password and email it to them so they can login and change it.  Fortunately, I found this neat little Ruby snippet that will generate random text of a given length:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;def generate_password(length=6)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
  password = ''
  length.times { |i| password &amp;lt;&amp;lt; chars[rand(chars.length)] }
  password
end&lt;/pre&gt;

&lt;p&gt;Some examples:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;generate_password
&amp;gt;&amp;gt; U48ydn

generate_password(10)
&amp;gt;&amp;gt; QzWXdAkDy5&lt;/pre&gt;</description>
      <pubDate>Thu, 07 Jun 2007 00:00:00 -0400</pubDate>
      <link>http://www.travisonrails.com/2007/06/07/Generate-random-text-with-Ruby</link>
    </item>
    <item>
      <title>Rails inline ERb effects on HTML structure</title>
      <description>&lt;p&gt;When using &lt;a href="http://www.rubyonrails.com"&gt;Ruby on Rails&lt;/a&gt;, ERb (embedded Ruby) is used a LOT in the X/HTML.  There are two types of ERb,&lt;/p&gt;

&lt;p&gt;An evaluation block:&lt;/p&gt;
&lt;pre name="code" class="xhtml"&gt;
&amp;lt;% some_code %&amp;gt;
&lt;/pre&gt;

&lt;p&gt;And an output block:&lt;/p&gt;
&lt;pre name="code" class="xhtml"&gt;
&amp;lt;%= @print_this_variable %&amp;gt;
&lt;/pre&gt;

&lt;p&gt;These blocks are necessary when using Rails, and I've noticed that when I do a 'View Source' (via the &lt;a href="https://addons.mozilla.org/firefox/60/"&gt;Web Developer addon&lt;/a&gt; for &lt;a href="http://www.getfirefox.com"&gt;Firefox&lt;/a&gt;, of course), I see a lot of funky spacing and line breaking where the ERb's have been evaluated.  Probably fine for most people, but it makes reading the outputted HTML code a hassle.&lt;/p&gt;

&lt;p&gt;It turns out that there are really three ways to use the evaluation ERb that can affect your spacing and line-breaking.&lt;/p&gt;

&lt;p&gt;Firstly, the output block is used just like you'd expect to use it.  If your code says this:&lt;/p&gt;

&lt;pre name="code" class="xhtml"&gt;
&amp;lt;p&amp;gt;
  Text before ERb.
  &amp;lt;%= "code_goes_here" %&amp;gt;
  Text after ERb
&amp;lt;/p&amp;gt;
&lt;/pre&gt;

&lt;p&gt;The resulting HTML will look just like this:&lt;/p&gt;

&lt;pre name="code" class="xhtml"&gt;
&amp;lt;p&amp;gt;
  Text before ERb.
  code_goes_here
  Text after ERb
&amp;lt;/p&amp;gt;
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Evaluation block use #1:&lt;/strong&gt;  If you just put a block, it will cause a line break after the block in the HTML, so if you had this in your code:&lt;/p&gt;

&lt;pre name="code" class="xhtml"&gt;
&amp;lt;p&amp;gt;
  Text before ERb.
  &amp;lt;% some_code %&amp;gt;
  Text after ERb
&amp;lt;/p&amp;gt;
&lt;/pre&gt;

&lt;p&gt;The resulting HTML code would look like this:&lt;/p&gt;

&lt;pre name="code" class="xhtml"&gt;
&amp;lt;p&amp;gt;
  Text before ERb.

  Text after ERb
&amp;lt;/p&amp;gt;
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Evaluation block use #2:&lt;/strong&gt;  If you add a dash(-) at the end of the block, it will prevent it from adding a line break.  So, if your code looks like this:&lt;/p&gt;

&lt;pre name="code" class="xhtml"&gt;
&amp;lt;p&amp;gt;
  Text before ERb.
  &amp;lt;% some_code -%&amp;gt;
  Text after ERb
&amp;lt;/p&amp;gt;
&lt;/pre&gt;

&lt;p&gt;The resulting HTML code would look like this:&lt;/p&gt;

&lt;pre name="code" class="xhtml"&gt;
&amp;lt;p&amp;gt;
  Text before ERb.
    Text after ERb
&amp;lt;/p&amp;gt;
&lt;/pre&gt;

&lt;p&gt;The line break is gone, but the space taken by the block is still there.  That leads us to. . . &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Evaluation block use #3:&lt;/strong&gt;  If you add a dash(-) at the beginning AND end of the block, it will prevent it from adding a line break AND remove the leading space it would have taken up.  So, if your code looks like this:&lt;/p&gt;

&lt;pre name="code" class="xhtml"&gt;
&amp;lt;p&amp;gt;
  Text before ERb.
  &amp;lt;%- some_code -%&amp;gt;
  Text after ERb
&amp;lt;/p&amp;gt;
&lt;/pre&gt;

&lt;p&gt;The resulting HTML code would look like this:&lt;/p&gt;

&lt;pre name="code" class="xhtml"&gt;
&amp;lt;p&amp;gt;
  Text before ERb.
  Text after ERb
&amp;lt;/p&amp;gt;
&lt;/pre&gt;

&lt;p&gt;You'd never know there was a code block there!  Is this useful?  I don't know... maybe.&lt;p&gt;</description>
      <pubDate>Sat, 31 Mar 2007 00:00:00 -0400</pubDate>
      <link>http://www.travisonrails.com/2007/03/31/Rails-inline-ERb-effects-on-HTML-structure</link>
    </item>
    <item>
      <title>Rails eager loading of associations</title>
      <description>&lt;p&gt;I ran into an interesting problem with table associations at &lt;a href="http://www.plexusweb.com"&gt;work&lt;/a&gt; the other day.  Below is a simple data model of the tables I was working with.  Basically, here's how it breaks down: A user is part of any given group (but only one group per user).  A document (any type) can be uploaded and assigned to a folder.  A group is used to assign viewing privileges to each document, so that every user in the group can see the document.  See below:&lt;/p&gt;

&lt;img src="/images/simple_datamodel.gif" alt="simple data model" /&gt;

&lt;p&gt;The problem came up because once a user is logged in, I need to get all of the folders that contain documents that the user's group has permission to see (a folder &lt;em&gt;could&lt;/em&gt; contain documents not viewable by the group).  I spent a few minutes scratching my head on how best to do a &lt;kbd&gt;find&lt;/kbd&gt; to get the results I needed.  I really couldn't come up with anything that would work.&lt;/p&gt;

&lt;p&gt;So, of course, when this happens, I do a little leg-stretching and walk over to &lt;a href="http://www.plexusweb.com/staff/adam"&gt;Adam&lt;/a&gt; and &lt;a href="http://www.plexusweb.com/staff/shawn"&gt;Shawn's&lt;/a&gt; space to ask them how they would do it.  After explaining the situation and a little white board art, they reminded me of eager loading of associations (which I've never really had to use).&lt;/p&gt;

&lt;p&gt;By using the &lt;kbd&gt;:include&lt;/kbd&gt; option in my &lt;kbd&gt;find&lt;/kbd&gt; method call, I can pre-load table associations to make my complex query a lot easier.  My code ended up looking like this:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;# find the logged-in user
user = User.find(session[:intranet_user])
# get all of the folders that contain documents they have access to
@folders = Folder.find(:all, :include =&gt; {:documents =&gt; {:groups =&gt; :users}}, :conditions =&gt; "users.id = #{user.id}" )&lt;/pre&gt;

&lt;p&gt;This worked perfectly!&lt;/p&gt;

&lt;p&gt;A note about eager loading of associations: they can save a lot of resources when used correctly.  Say you have a table called books and a table called authors, and each book has one author.  To get all of the books for display, you might put:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;@books = Book.find(:all)&lt;/pre&gt;

&lt;p&gt;Then, in your page, you might have:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;&amp;lt;% for book in @books -%&amp;gt;
	Title: &amp;lt;%= book.title %&amp;gt;
	Written by: &amp;lt;%= book.author.name %&amp;gt;
&amp;lt;% end -%&amp;gt;&lt;/pre&gt;

&lt;p&gt;Not only do you run a SQL query to get all of the books, you then run an additional query for each book to find it's author.  You can simplify this down to only one query, by using eager loading, like so:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;@books = Book.find(:all, :include =&gt; :author)&lt;/pre&gt;

&lt;p&gt;This pre-loads all of the data with only one SQL query.&lt;/p&gt;</description>
      <pubDate>Sun, 18 Feb 2007 00:00:00 -0500</pubDate>
      <link>http://www.travisonrails.com/2007/02/18/Rails-eager-loading-of-associations</link>
    </item>
  </channel>
</rss>
