<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Lasse Bunk&#039;s weblog &#187; Ruby on Rails</title>
	<atom:link href="http://lassebunk.dk/tag/ruby-on-rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://lassebunk.dk</link>
	<description>Ruby on Rails, programming, and SEO</description>
	<lastBuildDate>Sat, 04 Feb 2012 12:51:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Sitemap Notifier: Ruby on Rails plugin for notifying search engines of changes to sitemap</title>
		<link>http://lassebunk.dk/2011/09/18/sitemap-notifier/</link>
		<comments>http://lassebunk.dk/2011/09/18/sitemap-notifier/#comments</comments>
		<pubDate>Sun, 18 Sep 2011 19:08:16 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Bing]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[SEO]]></category>
		<category><![CDATA[Sitemaps]]></category>
		<category><![CDATA[Yahoo]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=2004</guid>
		<description><![CDATA[Ruby on Rails plugin that automatically notifies Google, Bing, and Yahoo when your models change.]]></description>
			<content:encoded><![CDATA[<p><a href="https://github.com/lassebunk/sitemap_notifier">Sitemap Notifier</a> is a <a href="http://rubyonrails.org">Ruby on Rails</a> plugin that, when installed, automatically notifies <a href="http://www.google.com">Google</a>, <a href="http://www.bing.com">Bing</a>, and <a href="http://www.yahoo.com">Yahoo</a> of changes to your models, i.e. changes to your <a href="http://www.sitemaps.org/">sitemap</a>. It also works in conjunction with the <a href="http://lassebunk.dk/2010/10/29/ruby-on-rails-sitemap-plugin/">Dynamic Sitemaps</a> plugin.</p>
<h3>Installation</h3>
<p>In Rails 3:</p>
<pre class="brush: bash; title: ; notranslate">
$ rails plugin install git://github.com/lassebunk/sitemap_notifier.git
</pre>
<h3>Example</h3>
<p>Start by generating initializer and route:</p>
<pre class="brush: bash; title: ; notranslate">
$ rails generate sitemap_notifier sitemap_notifier
</pre>
<p>In config/initializers/sitemap_notifier.rb:</p>
<pre class="brush: ruby; title: ; notranslate">
# wait 10 minutes between notifications
SitemapNotifier::Notifier.delay = 600

# replace this with your own url
SitemapNotifier::Notifier.sitemap_url = &quot;http://example.com/sitemap.xml&quot;
</pre>
<h3>After installation</h3>
<p>After you install and configure the plugin, it’ll automatically notify Google, Bing, and Yahoo every time you update a model. After each notification, it’ll wait 10 minutes (by default) before notifying again. This is to ensure that for example a batch update won’t trigger an equal amount of notifications.</p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/09/18/sitemap-notifier/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ApiBuilder: Ruby on Rails XML and JSON builder in one</title>
		<link>http://lassebunk.dk/2011/09/12/introducing-apibuilder-xml-and-json-builder-in-one/</link>
		<comments>http://lassebunk.dk/2011/09/12/introducing-apibuilder-xml-and-json-builder-in-one/#comments</comments>
		<pubDate>Mon, 12 Sep 2011 17:26:15 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Builder]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1966</guid>
		<description><![CDATA[ApiBuilder is a Ruby on Rails plugin that generates XML and JSON from a single specification.]]></description>
			<content:encoded><![CDATA[<p><a href="https://github.com/lassebunk/api_builder" title="ApiBuilder on GitHub">ApiBuilder</a> is a <a href="http://rubyonrails.org/">Ruby on Rails</a> template engine that allows for multiple formats being laid out in a single specification, currently XML and <a href="http://json.org/">JSON</a>. The template engine then returns a hash that is converted to either JSON or XML.</p>
<p>Like this:</p>
<p>In <em>app/views/api/users/index.apibuilder</em>:</p>
<pre class="brush: ruby; title: ; notranslate">
array :users do
  @users.each do |user|
    element :user do
      id @user.id
      name @user.name
    end
  end
end
</pre>
<p>Returns:</p>
<pre class="brush: jscript; title: ; notranslate">
[
  {
    &quot;id&quot;: 1234,
    &quot;name&quot;: &quot;Peter Jackson&quot;
  },
  {
    &quot;id&quot;: 1235,
    &quot;name&quot;: &quot;Marilyn Monroe&quot;
  }
]
</pre>
<p>And the equivalent XML.</p>
<p>In <em>app/views/api/users/show.apibuilder</em>:</p>
<pre class="brush: ruby; title: ; notranslate">
element :user do
  id @user.id
  name @user.name
  address do
    street @user.street
    city @user.city
  end
  array :interests do
    @user.interests.each do |interest|
      element :interest, interest.name
    end
  end
end
</pre>
<p>Returns:</p>
<pre class="brush: jscript; title: ; notranslate">
{
  &quot;id&quot;: 1234,
  &quot;name&quot;: &quot;Peter Jackson&quot;,
  &quot;address&quot;: {
    &quot;street&quot;: &quot;123 High Way&quot;,
    &quot;city&quot;: &quot;Gotham City&quot;
  },
  &quot;interests&quot;: [
    &quot;Movies&quot;,
    &quot;Computers&quot;,
    &quot;Internet&quot;
  ]
}
</pre>
<p>And the equivalent XML.</p>
<p>You can then call your API like this:</p>
<p><em>http://example.com/api/users?format=json</em></p>
<p>or</p>
<p><em>http://example.com/api/users?format=xml</em></p>
<p>and so on.</p>
<p>Installation:</p>
<pre class="brush: bash; title: ; notranslate">
$ rails plugin install git://github.com/lassebunk/api_builder.git
</pre>
<p>Documentation and examples: <a href="https://github.com/lassebunk/api_builder" title="ApiBuilder at GitHub">Check out ApiBuilder at GitHub</a>.<br />
Looking forward to comments and suggestions <img src='http://lassebunk.dk/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/09/12/introducing-apibuilder-xml-and-json-builder-in-one/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Creating a location aware website using Ruby on Rails and PostGIS</title>
		<link>http://lassebunk.dk/2011/09/10/creating-a-location-aware-website-using-ruby-on-rails-and-postgis/</link>
		<comments>http://lassebunk.dk/2011/09/10/creating-a-location-aware-website-using-ruby-on-rails-and-postgis/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 08:30:27 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Geospatial]]></category>
		<category><![CDATA[PostGIS]]></category>
		<category><![CDATA[PostgreSQL]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1863</guid>
		<description><![CDATA[How to create a location aware website using Ruby on Rails, PostgreSQL, and PostGIS.]]></description>
			<content:encoded><![CDATA[<p><a href="http://postgis.refractions.net/">PostGIS</a> is a geospatial extension to <a href="http://www.postgresql.org/">PostgreSQL</a> which gives a bunch of functions to handle geospatial data and queries, e.g. to find points of interest near a certain location, or storing a navigational route in your database. You can find the PostGIS documentation <a href="http://postgis.refractions.net/">here</a>.</p>
<p>In this example, I&#8217;ll show how to create a location aware website using <a href="http://rubyonrails.org/">Ruby on Rails</a>, PostgreSQL, and PostGIS. The application, when finished, will be able to store your current location – or a <em>check-in</em> – in the database, show all your check-ins on a map, and show check-ins nearby check-ins.</p>
<p>This app is written in Rails 3.1 but it could just as well be written in another version. As of writing, the current version of the <a href="https://github.com/fragility/spatial_adapter">spatial_adapter</a> gem has an <a href="https://github.com/fragility/spatial_adapter/issues/26">issue</a> in Rails 3.1 but we will create a workaround for this until it gets fixed.</p>
<p>You can <a href="https://github.com/lassebunk/checkins_app">view the complete source code</a> or <a href="http://test.lassebunk.dk/checkins/">see the final application in action</a>.</p>
<h3>Creating the PostGIS enabled database</h3>
<p>We will first create our geospatially enabled database. First check out out my post on <a href="http://lassebunk.dk/2011/09/08/installing-postgresql-and-postgis-on-mac-os-x/">installing PostgreSQL and PostGIS on Mac OS X</a>.</p>
<p>Create your database:</p>
<pre class="brush: bash; title: ; notranslate">
$ createdb -h localhost my_checkins_development
</pre>
<p>Install PostGIS in your database:</p>
<pre class="brush: bash; title: ; notranslate">
$ cd /opt/local/share/postgresql90/contrib/postgis-1.5/
$ psql -d my_checkins_development -f postgis.sql -h localhost
$ psql -d my_checkins_development -f spatial_ref_sys.sql -h localhost
</pre>
<p>Your database is now ready for geospatial queries.</p>
<h3>Creating the geospatially enabled Rails app</h3>
<p>Create your app:</p>
<pre class="brush: bash; title: ; notranslate">
$ rails new my_checkins
</pre>
<p>The <a href="https://github.com/fragility/spatial_adapter">spatial_adapter</a> gem is a plugin that adds geospatial functionality to Rails when using a PostgreSQL and PostGIS. It uses <a href="http://georuby.rubyforge.org/">GeoRuby</a> for data types. Add this and the pg (Postgres) gem to your <em>Gemfile</em>:</p>
<pre class="brush: ruby; title: ; notranslate">
gem 'spatial_adapter'
gem 'pg'
</pre>
<p>Run <code>bundle install</code>:</p>
<pre class="brush: bash; title: ; notranslate">
$ bundle install
</pre>
<p>Setup your <em>config/database.yml</em>:</p>
<pre class="brush: ruby; title: ; notranslate">
development:
  adapter: postgresql
  database: my_checkins_development
  host: localhost
</pre>
<p>And your app is geospatially enabled <img src='http://lassebunk.dk/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Creating the code to handle check-ins</h3>
<p>Let&#8217;s create some scaffold code to handle our check-ins:</p>
<pre class="brush: bash; title: ; notranslate">
$ rails g scaffold checkin title:string location:point
</pre>
<p>Take notice of the <em>point</em> data type – that&#8217;s a geospatial type.<br />
Before running your migrations, edit <em>db/migrate/create_checkins.rb</em>, replacing this:</p>
<pre class="brush: ruby; title: ; notranslate">
t.point :location
</pre>
<p>with this:</p>
<pre class="brush: ruby; title: ; notranslate">
t.point :location, :geographic =&gt; true
</pre>
<p>This tells your migration to add a geographic column that is set up to handle <a href="http://en.wikipedia.org/wiki/Geographic_coordinate_system">geographic coordinates</a>, also known as latitudes and longitudes.</p>
<p>Run your migrations:</p>
<pre class="brush: bash; title: ; notranslate">
$ rake db:migrate
</pre>
<p>We are now ready to store our check-ins.</p>
<p>The <em>Checkin</em> model now contains a <em>location</em> field which is a data type of <em>	GeoRuby::SimpleFeatures::Point</em>. This data type has properties of <em>x</em> and <em>y</em>. We will expose these as properties directly on the model. In <em>app/models/checkin.rb</em>:</p>
<pre class="brush: ruby; title: ; notranslate">
class Checkin &lt; ActiveRecord::Base
  def latitude
    (self.location ||= Point.new).y
  end

  def latitude=(value)
    (self.location ||= Point.new).y = value
  end

  def longitude
    (self.location ||= Point.new).x
  end

  def longitude=(value)
    (self.location ||= Point.new).x = value
  end
end
</pre>
<p>Latitude and longitude are now exposed.</p>
<p>In <em>app/views/checkins/_form.html.erb</em>, replace this:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;div class=&quot;field&quot;&gt;
  &lt;%= f.label :location %&gt;&lt;br /&gt;
  &lt;%= f.text_field :location %&gt;
&lt;/div&gt;
</pre>
<p>With this:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;div class=&quot;field&quot;&gt;
  &lt;%= f.label :latitude %&gt;&lt;br /&gt;
  &lt;%= f.text_field :latitude %&gt;
&lt;/div&gt;
&lt;div class=&quot;field&quot;&gt;
  &lt;%= f.label :longitude %&gt;&lt;br /&gt;
  &lt;%= f.text_field :longitude %&gt;
&lt;/div&gt;
</pre>
<p>If it wasn&#8217;t for a little <a href="https://github.com/fragility/spatial_adapter/issues/26">bug</a> in spatial_adapter under Rails 3.1, we would now be able to save locations from our Rails app. However, what the bug does is that it cannot create records when the location field is set. It <em>can</em> update them so what we will do is to make sure it first creates the check-in with a location set to <em>nil</em> and then updates it with the correct location. Like this, in <em>app/controllers/checkins_controller.rb</em> in the <em>create</em> method, replace this:</p>
<pre class="brush: ruby; title: ; notranslate">
def create
  ...
  if @checkin.save
    ...
</pre>
<p>With this:</p>
<pre class="brush: ruby; title: ; notranslate">
def create
  ...
  if @checkin.valid?
    location = @checkin.location
    @checkin.location = nil
    @checkin.save!
    @checkin.location = location
    @checkin.save!
    ...
</pre>
<p>And it should work.<br />
Try and fire up your server:</p>
<pre class="brush: bash; title: ; notranslate">
$ rails s
</pre>
<p>And go to <a href="http://localhost:3000/checkins/new">http://localhost:3000/checkins/new</a> in your browser.</p>
<p>Next, in <em>app/views/checkins/show.html.erb</em>, replace this:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;p&gt;
  &lt;b&gt;Location:&lt;/b&gt;
  &lt;%= @checkin.location %&gt;
&lt;/p&gt;
</pre>
<p>With this:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;p&gt;
  &lt;b&gt;Location:&lt;/b&gt;
  &lt;%= @checkin.latitude %&gt;, &lt;%= @checkin.longitude %&gt;
&lt;/p&gt;
</pre>
<p>And it will show the latitude and longitude you just entered.</p>
<h3>Getting our current location</h3>
<p>We would like to be able to create check-ins from our current location. Modern browsers exposes this functionality via a JavaScript <a href="http://dev.w3.org/geo/api/spec-source.html">API</a>. Create <em>app/assets/javascripts/checkins.js</em> and add this:</p>
<pre class="brush: jscript; title: ; notranslate">
function findMe() {
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      document.getElementById('checkin_latitude').value = position.coords.latitude;
      document.getElementById('checkin_longitude').value = position.coords.longitude;
    }, function() {
      alert('We couldn\'t find your position.');
    });
  } else {
    alert('Your browser doesn\'t support geolocation.');
  }
}
</pre>
<p>And a button in the top of <em>app/views/checkins/_form.html.erb</em>:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;input type=&quot;button&quot; value=&quot;Find me!&quot; onclick=&quot;findMe();&quot; /&gt;
</pre>
<p>Try it in your browser. If it gives you a JavaScript error saying the <em>findMe</em> method isn&#8217;t defined, try restarting your server to get the new javascript loaded. You should now be able to get your current location by clicking the <em>Find me!</em> button.</p>
<h3>Finding nearby check-ins</h3>
<p>Let&#8217;s create a method for finding nearby check-ins. PostGIS has a function named <em>ST_DWithin</em> which returns <em>true</em> if two locations are within a certain distance of each other. In <em>app/models/checkin.rb</em>, add the following to the top of the class:</p>
<pre class="brush: ruby; title: ; notranslate">
class Checkin &lt; ActiveRecord::Base
  scope :nearby_to,
    lambda { |location, max_distance|
      where(&quot;ST_DWithin(location, ?, ?) AND id != ?&quot;, checkin.location, max_distance, checkin.id)
    }
  ...
</pre>
<p>In <em>app/controllers/checkins_controller.rb</em>, add the following:</p>
<pre class="brush: ruby; title: ; notranslate">
def show
  @checkin = Checkin.find(params[:id])
  @nearby_checkins = Checkin.nearby_to(@checkin, 1000)
  ...
</pre>
<p>In <em>app/views/checkins/show.html.erb</em>, add the following just before the links in the bottom:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;h2&gt;Nearby check-ins&lt;/h2&gt;
&lt;ul&gt;
  &lt;% @nearby_checkins.each do |checkin| %&gt;
    &lt;li&gt;&lt;%= link_to checkin.title, checkin %&gt;&lt;/li&gt;
  &lt;% end %&gt;
&lt;/ul&gt;
</pre>
<p>It now shows all nearby checkins. Try adding a couple more based on your current location and see it in action.</p>
<h3>Creating a map with all check-ins</h3>
<p>Wouldn&#8217;t it be nice to show all our check-in on a map? We will do this using the <a href="http://code.google.com/apis/maps/index.html">Google Maps API</a>.</p>
<p>In <em>app/views/checkins/index.html.erb</em>, clear out the table and list, and add the following:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;http://maps.googleapis.com/maps/api/js?sensor=false&quot;&gt;&lt;/script&gt;
</pre>
<p>That loads the Google Maps JavaScript API functionality.</p>
<p>Create a <em>div</em> for the map:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;div id=&quot;map&quot; style=&quot;width: 600px; height: 500px;&quot;&gt;&lt;/div&gt;
</pre>
<p>And add the following script at the bottom:</p>
<pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;
  // Create the map
  var map = new google.maps.Map(document.getElementById(&quot;map&quot;), {
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Initialize the bounds container
  var bounds = new google.maps.LatLngBounds();

  &lt;% @checkins.each do |checkin| %&gt;
    // Create the LatLng
    var latLng = new google.maps.LatLng(&lt;%= checkin.latitude %&gt;, &lt;%= checkin.longitude %&gt;);

    // Create the marker
    var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        title: '&lt;%= escape_javascript(checkin.title) %&gt;'
    });

    // Add click event
    google.maps.event.addListener(marker, 'click', function() {
      document.location = '&lt;%= checkin_path(checkin) %&gt;';
    });

    // Extend the bounds
    bounds.extend(latLng);
  &lt;% end %&gt;

  // Fit to bounds
  map.fitBounds(bounds);
&lt;/script&gt;
</pre>
<p>There&#8217;s our map <img src='http://lassebunk.dk/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  Check it out at <a href="http://localhost:3000/checkins">http://localhost:3000/checkins</a>. Try creating some check-ins around the world to see the map expand.</p>
<h3>Conclusion</h3>
<p>That&#8217;s a location aware app that stores check-ins based on our current location, shows nearby check-ins, and displays check-ins on a map.</p>
<p><a href="https://github.com/lassebunk/checkins_app">View the complete source code</a> or <a href="http://test.lassebunk.dk/checkins/">see the final application in action</a>.</p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/09/10/creating-a-location-aware-website-using-ruby-on-rails-and-postgis/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Deploying a Rails 3.1 app to subdirectory in Apache</title>
		<link>http://lassebunk.dk/2011/09/09/deploying-a-rails-3-1-app-to-subdirectory-in-apache/</link>
		<comments>http://lassebunk.dk/2011/09/09/deploying-a-rails-3-1-app-to-subdirectory-in-apache/#comments</comments>
		<pubDate>Fri, 09 Sep 2011 21:09:47 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[Configuration]]></category>
		<category><![CDATA[Server]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1929</guid>
		<description><![CDATA[How to deploy a Rails 3.1 app to a subdirectory in Apache.]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s how to deploy a Rails 3.1 app to a subdirectory in Apache, replacing <code>config.action_controller.relative_url_root</code> which no longer exists.</p>
<p>In <em>config/routes.rb</em>:</p>
<pre class="brush: ruby; title: ; notranslate">
scope 'my_subdir' do
  # all resources and routes go here
end
</pre>
<p>In your Apache configuration file:</p>
<pre class="brush: bash; title: ; notranslate">
Alias /my_subdir /var/www/my_subdir/public
&lt;Location /my_subdir&gt;
  SetEnv RAILS_RELATIVE_URL_ROOT &quot;/my_subdir&quot;
  PassengerAppRoot /var/www/my_subdir
&lt;/Location&gt;
</pre>
<p>And it should work, including automatically pointing all your assets to <em>/my_subdir</em>.</p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/09/09/deploying-a-rails-3-1-app-to-subdirectory-in-apache/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is Ruby on Rails? (an introduction)</title>
		<link>http://lassebunk.dk/2011/09/05/what-is-ruby-on-rails-an-introduction/</link>
		<comments>http://lassebunk.dk/2011/09/05/what-is-ruby-on-rails-an-introduction/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 12:40:37 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Introduction]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1792</guid>
		<description><![CDATA[An introduction to the Ruby on Rails framework.]]></description>
			<content:encoded><![CDATA[<p>So what is <a href="http://rubyonrails.org/">Ruby on Rails</a>? Here&#8217;s an introduction.</p>
<h3>Ruby (the programming language)</h3>
<p>From <a href="http://en.wikipedia.org/wiki/Ruby_%28programming_language%29">Wikipedia</a>: &#8220;Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro &#8220;Matz&#8221; Matsumoto. It was influenced primarily by Perl, Smalltalk, Eiffel, and Lisp.&#8221; Ruby is a beautiful language – you&#8217;ll love it. Read more on <a href="http://www.ruby-lang.org/en/">ruby-lang.org</a> and <a href="http://tryruby.org/">try it here</a>.</p>
<h3>Rails (the framework)</h3>
<p>Rails is a web framework built on Ruby, hence the name Ruby on Rails. It enables the programmer to easily create advanced websites, following <a href="http://en.wikipedia.org/wiki/Convention_over_configuration">convention over configuration</a>, which means that if you stick to a certain set of conventions, a lot of features will work right out of the box with very little code.</p>
<h3>MVC (Model-View-Controller)</h3>
<p>Rails is based on a programming pattern called MVC, which stands for Model-View-Controller. Here I&#8217;ll try to explain what it is and why it makes sense to use it.</p>
<h4>Model</h4>
<p>The model in MVC is a class for each entity in your application. Example models are <em>User</em>, <em>Category</em>, or <em>Product</em>. The models hold all business logic, for example what should happen if you delete a product, add a new category, or create a new user. </p>
<h4>View</h4>
<p>The views in MVC hold all your presentation and presentation logic, normally HTML. It is based on <a href="http://en.wikipedia.org/wiki/ERuby">ERuby</a> which is a templating system that allows for Ruby embedded into HTML and other languages. You probably know this kind of templating system from ASP, PHP, or JSP.</p>
<h4>Controller</h4>
<p>The controller is what binds together the models and views, for example tells the <em>show product</em> view which product it should show, or handles the data from a form post when a user updates a shopping basket.</p>
<h4>Why does MVC make sense?</h4>
<p>MVC allows for perfect separation of business logic from presentation logic, giving you a much cleaner application that is easier to maintain and, on top of that, a lot more fun to develop.</p>
<h3>Routing</h3>
<p>So, how does is a request from a visitors browser sent down to the controller that handles this request? This is done by a routing engine that interprets the request and passes it on to the matching controller.</p>
<h4>CRUD (Create, Read, Update, Delete)</h4>
<p>In the heart of the Rails routing engine lies <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a>, or <em>Create</em>, <em>Read</em>, <em>Update</em>, <em>Delete</em>, which comes from a notion that all web pages are made up of these four actions. For example, you <em>create</em> a product, view, or <em>read</em> a user, edit, or <em>update</em> a category, and <em>delete</em> an order.</p>
<p>If you follow this pattern, you&#8217;ll get a lot of work done for you. For example, all it takes to create all of these actions for a product is to tell the routing engine that you have an entity called product, and it will wire up all the routing logic that binds the request to the matching controller for you.</p>
<h3>ActiveRecord</h3>
<p><a href="http://en.wikipedia.org/wiki/Active_record_pattern">ActiveRecord</a> is a pattern that allows for all database access to be written without a single line of database access. You tell the class, or model, what kind of entity you want it to be, which relations it has, and it automagically does the rest for you, creating properties based on the fields from the database, giving you database operation methods like create, update, and delete for free. You write only your custom business logic. The ActiveRecord classes are almost always what makes up the <em>Model</em> part of the aforementioned MVC pattern.</p>
<h3>Database migrations</h3>
<p>In Ruby on Rails you almost never talk directly to your database like you know it from PHP or other scripting languages. Instead, as part of ActiveRecord, comes a complete database migration framework. Database migrations mean that you create Ruby code for creating tables and adding columns instead of doing this directly in your database. What this does it that it allows for migrating multiple databases with the same changes, for example a development and production database, without having to remember what changes you made in your development database when deploying to production – you just run the same migrations in a different environment.</p>
<h3>Separation of environments (development, production, etc.)</h3>
<p>In Rails, you have a perfect separation of environments. This means that you can run your system with different settings based on which environment you are currently in, for example you want your development environment to display verbose error messages where your production site shows a user friendly message to the end user.</p>
<h3>Assets management (images, stylesheets, and javascripts)</h3>
<p>The Rails 3.1 assets pipeline allows for all your assets (images, stylesheets, and javascripts) to be managed for you. In your development environment you have your full folder structure with stylesheets and javascripts written in different languages like CoffeeScript and SCSS. When you deploy, all your assets are compiled and fetched from the same folder, all stylesheets compiled together, the same with your javascripts. This also means that you don&#8217;t have to include for example <a href="http://jquery.com/">jQuery</a> – this is included for you via the <a href="https://github.com/indirect/jquery-rails">jQuery Rails</a> plugin.</p>
<h3>Plugins (RubyGems etc.)</h3>
<p>Coding in Ruby on Rails means that you get a butt load of plugins already written for you. Not in the Rails core (it&#8217;s very clean) but as <a href="http://rubygems.org/">RubyGems</a> which is a kind of packaging for Ruby. For example, you could have plugins for <a href="https://github.com/mislav/will_paginate">pagination</a>, <a href="http://lassebunk.dk/2011/03/09/rails-seo-pack/">search engine optimization</a>, or <a href="https://github.com/thoughtbot/paperclip">image processing</a>. As of the time of writing, there are over 27,000 RubyGems to be used for free.</p>
<h3>Conclusion</h3>
<p>Ruby on Rails is a great framework for creating advanced web applications writing very little code in comparison to what you get. I recommend it for almost any kind of application, and especially for prototyping. To inspire you, I created a <a href="http://lassebunk.dk/2011/03/17/blog-in-less-than-10-minutes-using-ruby-on-rails/">video</a> where I create a blog in 10 minutes using Ruby on Rails. Check it out and be sold. I also recommend the <a href="http://rubyonrails.org/documentation">documentation section</a> of the <a href="http://rubyonrails.org/">official Ruby on Rails site</a>. For those of you used to Ruby on Rails, I recommend <a href="http://weblog.rubyonrails.org/2011/8/31/rails-3-1-0-has-been-released">this blog post</a> about the changes from version 3.0 to version 3.1.</p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/09/05/what-is-ruby-on-rails-an-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Leveraging Rails 3.1, SCSS, and the assets pipeline to differentiate your stylesheets</title>
		<link>http://lassebunk.dk/2011/09/04/leveraging-rails-3-1-scss-and-the-assets-pipeline/</link>
		<comments>http://lassebunk.dk/2011/09/04/leveraging-rails-3-1-scss-and-the-assets-pipeline/#comments</comments>
		<pubDate>Sat, 03 Sep 2011 23:42:10 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Assets]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[SCSS]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1755</guid>
		<description><![CDATA[How to differentiate your stylesheets, and have different page styles using Rails 3.1, SCSS and the assets pipeline.]]></description>
			<content:encoded><![CDATA[<p>So, you&#8217;ve got different stylesheets and want to upgrade to the Rails 3.1 assets pipeline? The challenge by doing this is that all stylesheets will be compiled together in one file so therefore we need another method to differentiate our sites.</p>
<p>Here I will show how to use SCSS/CSS on the <em>body</em>-tag to differentiate between two different sites, and between the various pages on each site.</p>
<h3>1. Differentiating your content</h3>
<p>Let&#8217;s say that you are building a mobile and desktop site and want to differentiate your content sitewise. (If you&#8217;re building a mobile site, the actual server-side separation of the content can be done with a plugin like <a href="https://github.com/brendanlim/mobile-fu">mobile-fu</a> which works really great.)</p>
<p>Start by inserting a <em>desktop</em> and <em>mobile</em> class in your <em>body</em>-tags, like this:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;body class=&quot;desktop&quot;&gt;
</pre>
<p>and for your mobile site:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;body class=&quot;mobile&quot;&gt;
</pre>
<p>Next, add the following method to your <em>application_helper.rb</em>:</p>
<pre class="brush: ruby; title: ; notranslate">
def find_named_routes
  routes = []

  Rails.application.routes.named_routes.each do |name, route|
    req = route.requirements
    if req[:controller] == params[:controller] &amp;&amp; req[:action] == params[:action]
      routes &lt;&lt; name
    end
  end

  routes
end
</pre>
<p>This method will find all named routes based on the current controller and action. It will also find duplicate routes and localized routes if you are using a route translation gem like <a href="https://github.com/kwi/i18n_routing">i18n_routing</a>.</p>
<p>Now you can add the method to your <em>body</em>-tags like this:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;body class=&quot;desktop &lt;%= find_named_routes.join(&quot; &quot;) %&gt;&quot;&gt;
</pre>
<p>This way you&#8217;ll get <em>body</em>-classes like <em>root</em>, <em>categories</em>, <em>category</em> and so on. These can be used to differentiate your content later on. We will do this using <em>SCSS</em>.</p>
<h3>2. Creating the CSS</h3>
<p><a href="http://sass-lang.com/">SCSS</a> is an extension to CSS which among a lot of other feature allows you to nest your content. Instead of:</p>
<pre class="brush: css; title: ; notranslate">
.blah ul { ... }
.blah p { ... }
.blah a { ... }
</pre>
<p>In SCSS you can do it like this:</p>
<pre class="brush: css; title: ; notranslate">
.blah {
  ul { ... }
  p { ... }
  a { ... }
}
</pre>
<p>And it will generate the exact same CSS. Neat, eh?</p>
<p>So now we can use this technique to differentiate our sites and individual pages. Like this, in <em>desktop.css.scss</em>:</p>
<pre class="brush: css; title: ; notranslate">
body.desktop {
  margin: 20px;
  font-family: arial, helvetica, sans-serif;
  a { color: black }
  p { margin-bottom: 10px; }
  h1 { color: green; }
}
</pre>
<p>In <em>categories.css.scss</em>:</p>
<pre class="brush: css; title: ; notranslate">
body.desktop.categories {
  h1 { color: red; }
}
</pre>
<p>And in <em>mobile.css.scss</em>:</p>
<pre class="brush: css; title: ; notranslate">
body.mobile {
  margin: 10px;
  font-family: arial, helvetica, sans-serif;
  a { color: red }
  p { margin-bottom: 5px }
}
</pre>
<p>Pretty sweet. Now you just need to compile your assets, and you&#8217;re good to go.</p>
<p>Also see my other post about <a href="http://lassebunk.dk/2011/09/03/getting-your-assets-to-work-when-upgrading-to-rails-3-1/">how to get your assets to work in Rails 3.1</a>.</p>
<p><strong>Update:</strong> And the answer to this Stack Overflow question: <a href="http://stackoverflow.com/questions/7134034/using-rails-3-1-assets-pipeline-to-conditionally-use-certain-css/7273333#7273333">Using Rails 3.1 assets pipeline to conditionally use certain css</a></p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/09/04/leveraging-rails-3-1-scss-and-the-assets-pipeline/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting your assets to work when upgrading to Rails 3.1</title>
		<link>http://lassebunk.dk/2011/09/03/getting-your-assets-to-work-when-upgrading-to-rails-3-1/</link>
		<comments>http://lassebunk.dk/2011/09/03/getting-your-assets-to-work-when-upgrading-to-rails-3-1/#comments</comments>
		<pubDate>Sat, 03 Sep 2011 17:39:12 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Assets]]></category>
		<category><![CDATA[Capistrano]]></category>
		<category><![CDATA[Deployment]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1720</guid>
		<description><![CDATA[How to get the new Rails 3.1 assets pipeline working when upgrading or migrating from a Rails 3.0 app.]]></description>
			<content:encoded><![CDATA[<p>I was upgrading an app from Rails 3.0 to Rails 3.1 and had some trouble when it came to assets. Here&#8217;s how I got it to work.</p>
<h3>1. Upgrading to Rails 3.1</h3>
<p>Add Rails 3.1 to your Gemfile. Add or change the <code>gem 'rails'</code> line:</p>
<pre class="brush: ruby; title: ; notranslate">
gem 'rails', '3.1.0'
</pre>
<p>Bundle install:</p>
<pre class="brush: bash; title: ; notranslate">
$ bundle install
</pre>
<p>Run the update task to get your Rails files up to date, but beware! Just overwriting all files will probably mess up your app, so make sure to backup files or take notice of what changes you need to add to the new files before overwriting them. It will ask you what to do:</p>
<pre class="brush: bash; title: ; notranslate">
$ rake rails:update
</pre>
<p>Now your app should be running Rails 3.1. You can try running it using <code>rails s</code> but it probably won&#8217;t look great because we&#8217;ve not yet migrated the assets.</p>
<h3>2. Migrating your assets</h3>
<p>Try switching off the assets pipeline by commenting out the following line in <code>config/application.rb</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
# config.assets.enabled = true
</pre>
<p>Your app should now be running as usual. If it doesn&#8217;t, try ironing out any issues before switching on the assets again:</p>
<pre class="brush: ruby; title: ; notranslate">
config.assets.enabled = true
</pre>
<p>We&#8217;re now ready to migrate the assets.</p>
<p>First, add this to your <code>Gemfile</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
gem 'jquery-rails'
group :assets do
  gem 'sass-rails', &quot;  ~&gt; 3.1.0&quot;
  gem 'coffee-rails', &quot;~&gt; 3.1.0&quot;
  gem 'uglifier'
end
</pre>
<p>And install:</p>
<pre class="brush: bash; title: ; notranslate">
$ bundle install
</pre>
<p>Now to the actual migration:</p>
<ol>
<li>Make sure you have the <code>images</code>, <code>javascripts</code>, and <code>stylesheets</code> folders in your <code>app/assets</code> folder.</li>
<li>Move all content from <code>public/images</code> into <code>app/assets/images</code>.</li>
<li>Move all content from <code>public/javascripts</code> into <code>app/assets/javascripts</code>.</li>
<li>Move all content from <code>public/stylesheets</code> into <code>app/assets/stylesheets</code>.</li>
</ol>
<p>Your javascripts and stylesheets will be compiled into a single <code>application.js</code> and <code>application.css</code>, so add or change this in your <code>app/views/layouts/application.html.erb</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;%= stylesheet_link_tag 'application' %&gt;
&lt;%= javascript_include_tag 'application' %&gt;
</pre>
<p>To make sure that the assets generator will find all your javascripts and stylesheets, we will include all your javascripts in <code>application.js</code> and all your stylesheets in <code>application.css</code>. Assuming you are using jQuery, you can delete <code>jquery.js</code> and <code>jquery-ui.js</code> as they will be required and inserted automatically. Add the following to the top of <code>app/assets/javascripts/application.js</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
//= require jquery
//= require jquery_ujs
//= require_tree .
</pre>
<p>And to the top of <code>app/assets/stylesheets/application.css</code>:</p>
<pre class="brush: css; title: ; notranslate">
/*
 *= require_self
 *= require_tree .
*/
</pre>
<p>Your javascripts and stylesheets will now be included automatically.</p>
<p>At last update all your image paths from <code>/images</code> to <code>/assets</code>. If you&#8217;re using the <code>image_tag</code> helper, all paths will be updated automatically.</p>
<h3>3. Deploying your assets</h3>
<p>Assuming you are deploying using <a href="https://github.com/capistrano/capistrano">Capistrano</a>, add the following to your <code>config/deploy.rb</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
before &quot;deploy:symlink&quot;, &quot;assets:precompile&quot;

namespace :assets do
  desc &quot;Compile assets&quot;
  task :precompile, :roles =&gt; :app do
    run &quot;cd #{release_path} &amp;&amp; rake RAILS_ENV=#{rails_env} assets:precompile&quot;
  end
end
</pre>
<p>Your assets will now be compiled right before your app is moved into place in your production environment.</p>
<p>Try deploying your app:</p>
<pre class="brush: bash; title: ; notranslate">
$ cap deploy
</pre>
<p>If the deployment went as expected, great. If you get an error complaining about a missing JavaScript engine, try adding the following to the <code>assets</code> section of your <code>Gemfile</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
gem 'therubyracer'
</pre>
<p>And run the deployment again.</p>
<p>Your assets should now be in place! If you run into other problems, please write a comment below, and I&#8217;ll see if I can help.</p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/09/03/getting-your-assets-to-work-when-upgrading-to-rails-3-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Implementing multiple text formats in Rails</title>
		<link>http://lassebunk.dk/2011/03/28/rails-multiple-text-formats/</link>
		<comments>http://lassebunk.dk/2011/03/28/rails-multiple-text-formats/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 07:30:21 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Markdown]]></category>
		<category><![CDATA[Text formats]]></category>
		<category><![CDATA[Textile]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1092</guid>
		<description><![CDATA[How to implement multiple text formats in Ruby on Rails.]]></description>
			<content:encoded><![CDATA[<p>So, maybe you&#8217;re building your own article system (or blog or content management system) and want to be able to choose from more than just one format when writing articles.</p>
<p>Create an <code>Article</code> model using scaffolding to have the controller and views generated automatically:</p>
<pre class="brush: bash; title: ; notranslate">
$ rails g scaffold Article title:string content:text format:string
</pre>
<p>Migrate:</p>
<pre class="brush: bash; title: ; notranslate">
$ rake db:migrate
</pre>
<p>In <code>app/models/article.rb</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
class Article &lt; ActiveRecord::Base
  FORMATS = [[&quot;HTML&quot;, &quot;html&quot;],
             [&quot;Markdown&quot;, &quot;markdown&quot;],
             [&quot;Textile&quot;, &quot;textile&quot;],
             [&quot;Plain text&quot;, &quot;plain&quot;]]
  validates_inclusion_of :format,
                         :in =&gt; FORMATS.collect { |name, format| format }
end
</pre>
<p>In <code>app/views/articles/_form.html.erb</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;% form_for(@article) do |f| %&gt;
  &lt;p&gt;
    &lt;%= f.label :title %&gt;&lt;br /&gt;
    &lt;%= f.text_field :title %&gt;
  &lt;/p&gt;
  &lt;p&gt;
    &lt;%= f.label :format %&gt;&lt;br /&gt;
    &lt;%= f.select :format, Article::FORMATS %&gt;
  &lt;/p&gt;
  &lt;p&gt;
    &lt;%= f.label :content %&gt;&lt;br /&gt;
    &lt;%= f.text_area :content %&gt;
  &lt;/p&gt;
  &lt;p&gt;
    &lt;%= f.submit %&gt;
  &lt;/p&gt;
&lt;% end %&gt;
</pre>
<p>In <code>app/helpers/articles_helper.rb</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
module ArticlesHelper
  def format_content(format, content)
    case format
    when &quot;html&quot;
      content.html_safe
    when &quot;markdown&quot;
      BlueCloth.new(content).to_html.html_safe
    when &quot;textile&quot;
      RedCloth.new(content).to_html.html_safe
    when &quot;plain&quot;
      simple_format(html_escape(content))
    else
      raise ArgumentError, &quot;Unknown format '#{format}'.&quot;
    end
  end
end
</pre>
<p>In <code>app/views/articles/show.html.erb</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;h1&gt;&lt;%=h @article.title %&gt;&lt;/h1&gt;
&lt;%= format_content(@article.format, @article.content) %&gt;
</pre>
<p>Add the RedCloth and BlueCloth gems to your <code>Gemfile</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
gem 'RedCloth'  # textile
gem 'bluecloth' # markdown
</pre>
<p>Install the gems:</p>
<pre class="brush: bash; title: ; notranslate">
$ bundle install
</pre>
<p>It&#8217;s as easy as that. Now you can create articles, choose a format, and this format will be used to render the content of the article.</p>
<p>Did you find this helpful? Please let me know in the comments.</p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/03/28/rails-multiple-text-formats/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails: Saving multiple models only if all are valid</title>
		<link>http://lassebunk.dk/2011/03/21/rails-multiple-models-validation/</link>
		<comments>http://lassebunk.dk/2011/03/21/rails-multiple-models-validation/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 08:30:54 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[Multiple models]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1184</guid>
		<description><![CDATA[How to save multiple models in Ruby on Rails only if all validate.]]></description>
			<content:encoded><![CDATA[<p>So, what do you do if you have multiple models in one form independent of each other and you want to save them all at once, but only if they all validate?</p>
<p>In the controller:</p>
<pre class="brush: ruby; title: ; notranslate">
def new
  @account = Account.new
  @user = User.new
end
</pre>
<p>In the view:</p>
<pre class="brush: ruby; title: ; notranslate">
&lt;%= form_for @account do |f| %&gt;
  &lt;%= f.error_messages %&gt;
  &lt;p&gt;
    &lt;%= f.label :name %&gt;&lt;br /&gt;
    &lt;%= f.text_field :name %&gt;
  &lt;/p&gt;
  &lt;%= fields_for @user do |u| %&gt;
    &lt;%= u.error_messages %&gt;
    &lt;p&gt;
      &lt;%= u.label :name %&gt;&lt;br /&gt;
      &lt;%= u.text_field :name %&gt;
    &lt;/p&gt;
  &lt;% end %&gt;
  &lt;p&gt;
    &lt;%= f.submit &quot;Create account&quot; %&gt;
  &lt;/p&gt;
&lt;% end %&gt;
</pre>
<p>And after you press &#8216;Create account&#8217; – in the controller:</p>
<pre class="brush: ruby; title: ; notranslate">
def create
  @account = Account.new(params[:account])
  @user = User.new(params[:user])

  if [@account, @user].map { |rec| rec.valid? }.all?
    [@account, @user].each { |rec| rec.save! }
    redirect_to account_path
  else
    render :new
  end
end
</pre>
<p>This way each model will only be saved if all models validate.</p>
<p>And, this could be done even nicer by writing a method. In your <code>ApplicationController</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
def save_all(*models)
  if models.map { |rec| rec.valid? }.all?
    models.each { |rec| rec.save! }
    true
  end
end
</pre>
<p>In your controller:</p>
<pre class="brush: ruby; title: ; notranslate">
if save_all(@account, @user)
  redirect_to account_path
else
  render :new
end
</pre>
<p><strong>Note:</strong> To use <code>form.error_messages</code> in Rails 3, you need <a href="http://github.com/rails/dynamic_form">this plugin</a>.</p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/03/21/rails-multiple-models-validation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Blog in less than 10 minutes using Ruby on Rails</title>
		<link>http://lassebunk.dk/2011/03/17/blog-in-less-than-10-minutes-using-ruby-on-rails/</link>
		<comments>http://lassebunk.dk/2011/03/17/blog-in-less-than-10-minutes-using-ruby-on-rails/#comments</comments>
		<pubDate>Thu, 17 Mar 2011 21:04:05 +0000</pubDate>
		<dc:creator>lassebunk</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[Screencast]]></category>

		<guid isPermaLink="false">http://lassebunk.dk/?p=1672</guid>
		<description><![CDATA[Screencast of how to create a blog in less than 10 minutes using Ruby on Rails.]]></description>
			<content:encoded><![CDATA[<p>The one video that got me <a href="http://lassebunk.dk/2009/09/24/three-months-on-the-mac-stack/" title="Three months on the Mac stack">convinced</a> to buy a Mac and learn <a href="http://rubyonrails.org">Ruby on Rails</a> was a video called <a href="http://vimeo.com/5362441">Building a blog in 15 minutes</a>. The video showed how to build a blog in 15 minutes using Ruby on Rails.</p>
<p>But could this be done in <strong>less than 10 minutes</strong> using Rails 3? See for yourself <img src='http://lassebunk.dk/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><iframe title="YouTube video player" width="560" height="349" src="http://www.youtube.com/embed/JaL9ul17kx0?hd=1" frameborder="0"></iframe></p>
<p><a href="/downloads/Blog in less than 10 minutes using Ruby on Rails.mov">Download the video in HD quality</a></p>
<p>
<a href="http://twitter.com/lassebunk" onclick="abtest.trackGoal(21, this);" class="icon twitter">Follow me on Twitter</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://lassebunk.dk/2011/03/17/blog-in-less-than-10-minutes-using-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

