<?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>Biodegradable Geek &#187; SQL</title>
	<atom:link href="http://biodegradablegeek.com/category/database-sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://biodegradablegeek.com</link>
	<description></description>
	<lastBuildDate>Tue, 22 Jun 2010 21:52:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Quick BASH Script to Dump &amp; Compress a MySQL Database</title>
		<link>http://biodegradablegeek.com/2008/12/quick-bash-script-to-dump-compress-a-mysql-database/</link>
		<comments>http://biodegradablegeek.com/2008/12/quick-bash-script-to-dump-compress-a-mysql-database/#comments</comments>
		<pubDate>Sat, 27 Dec 2008 18:01:19 +0000</pubDate>
		<dc:creator>Isam</dc:creator>
				<category><![CDATA[Automation]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[backups]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://biodegradablegeek.com/?p=299</guid>
		<description><![CDATA[A quick script I whipped up to dump my MySQL database.
Usage: sh backthatsqlup.sh
(be warned that it dumps ALL databases. This can get huge uncompressed)

#!/bin/sh
# Isam (Biodegradablegeek.com) public domain 12/28/2008
# Basic BASH script to dump and compress a MySQL dump
&#160;
out=sequel_`date +'%m%d%Y_%M%S'`.sql
dest=/bx/
&#160;
function e &#123;
  echo -e &#34;n** $1&#34;
&#125;
&#160;
e &#34;Dumping SQL file ($out). May take awhile...&#34;
#echo &#34;oh [...]]]></description>
			<content:encoded><![CDATA[<p>A quick script I whipped up to dump my MySQL database.<br />
<strong>Usage: sh backthatsqlup.sh</strong></p>
<p><em>(be warned that it dumps ALL databases. This can get huge uncompressed)</em></p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/sh</span>
<span style="color: #666666; font-style: italic;"># Isam (Biodegradablegeek.com) public domain 12/28/2008</span>
<span style="color: #666666; font-style: italic;"># Basic BASH script to dump and compress a MySQL dump</span>
&nbsp;
<span style="color: #007800;">out</span>=sequel_<span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">date</span> +<span style="color: #ff0000;">'%m%d%Y_%M%S'</span><span style="color: #000000; font-weight: bold;">`</span>.sql
<span style="color: #007800;">dest</span>=<span style="color: #000000; font-weight: bold;">/</span>bx<span style="color: #000000; font-weight: bold;">/</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> e <span style="color: #7a0874; font-weight: bold;">&#123;</span>
  <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-e</span> <span style="color: #ff0000;">&quot;n** $1&quot;</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
e <span style="color: #ff0000;">&quot;Dumping SQL file (<span style="color: #007800;">$out</span>). May take awhile...&quot;</span>
<span style="color: #666666; font-style: italic;">#echo &quot;oh snap&quot; &amp;gt; $out</span>
<span style="color: #c20cb9; font-weight: bold;">sudo</span> mysqldump <span style="color: #660033;">-u</span> root <span style="color: #660033;">-p</span> <span style="color: #660033;">--all-databases</span> <span style="color: #000000; font-weight: bold;">&amp;</span>gt; <span style="color: #007800;">$out</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$?</span> <span style="color: #660033;">-ne</span> <span style="color: #000000;">0</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
  e <span style="color: #ff0000;">&quot;MySQL dump failed. Check that server is up and your username/pass&quot;</span>
  <span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #000000;">7</span>
<span style="color: #000000; font-weight: bold;">fi</span>
&nbsp;
e <span style="color: #ff0000;">&quot;Uncompressed SQL file size&quot;</span>
<span style="color: #c20cb9; font-weight: bold;">du</span> <span style="color: #660033;">-hs</span> <span style="color: #007800;">$out</span>
&nbsp;
e <span style="color: #ff0000;">&quot;Compressing SQL file&quot;</span>
<span style="color: #007800;">gz</span>=<span style="color: #007800;">$out</span>.tar.gz
<span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-zvvcf</span> <span style="color: #007800;">$gz</span> <span style="color: #007800;">$out</span>
<span style="color: #007800;">rt</span>=<span style="color: #007800;">$?</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$rt</span> <span style="color: #660033;">-ne</span> <span style="color: #000000;">0</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
  e <span style="color: #ff0000;">&quot;tar failed (error=<span style="color: #007800;">$rt</span>). Will NOT remove uncompressed SQL file&quot;</span>
<span style="color: #000000; font-weight: bold;">else</span>
  e <span style="color: #ff0000;">&quot;Removing uncompressed SQL file&quot;</span>
  <span style="color: #c20cb9; font-weight: bold;">rm</span> <span style="color: #660033;">-f</span> <span style="color: #007800;">$out</span>
  <span style="color: #007800;">out</span>=<span style="color: #007800;">$gz</span>
&nbsp;
  e <span style="color: #ff0000;">&quot;Compressed SQL file size&quot;</span>
  <span style="color: #c20cb9; font-weight: bold;">du</span> <span style="color: #660033;">-hs</span> <span style="color: #007800;">$out</span>
<span style="color: #000000; font-weight: bold;">fi</span>
&nbsp;
e <span style="color: #ff0000;">&quot;Moving shit to '<span style="color: #007800;">$dest</span>'&quot;</span>
<span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">mv</span> <span style="color: #007800;">$out</span> <span style="color: #007800;">$dest</span></pre></div></div>

<p><a href="http://code.biodegradablegeek.com/backthatsqlup.sh">BackThatSqlUp.sh</a></p>
]]></content:encoded>
			<wfw:commentRss>http://biodegradablegeek.com/2008/12/quick-bash-script-to-dump-compress-a-mysql-database/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How To Use Fixtures to Populate Your Database in Rails</title>
		<link>http://biodegradablegeek.com/2008/07/how-to-use-fixtures-to-populate-your-database-in-rails/</link>
		<comments>http://biodegradablegeek.com/2008/07/how-to-use-fixtures-to-populate-your-database-in-rails/#comments</comments>
		<pubDate>Fri, 11 Jul 2008 05:58:56 +0000</pubDate>
		<dc:creator>Isam</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[fixtures]]></category>
		<category><![CDATA[migrations]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[phpunit]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://biodegradablegeek.com/?p=121</guid>
		<description><![CDATA[UPDATE: I&#8217;ve been using this method for awhile now: http://railspikes.com/2008/2/1/loading-seed-data
Seed data is data that the app is dependent on. It is data that has to exist if you were to wipe the database clean and reload your schema. Some examples would be a list of cities/states, a list of categories, or the initial &#8216;admin&#8217; user [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE: I&#8217;ve been using this method for awhile now: <a href="http://railspikes.com/2008/2/1/loading-seed-data" target="_blank">http://railspikes.com/2008/2/1/loading-seed-data</a></strong></p>
<p>Seed data is data that the app is dependent on. It is data that has to exist if you were to wipe the database clean and reload your schema. Some examples would be a list of cities/states, a list of categories, or the initial &#8216;admin&#8217; user account.</p>
<p>Most people looking at this thread want seed data rather than to populate their database with test/generated content. For the latter, you can go the route below or try <a href="http://github.com/sevenwire/forgery/tree/master" target="_blank">Forgery </a></p>
<p>&#8212;</p>
<p><em>This is a response to the email I&#8217;ve been getting asking me how to use fixtures to load data into a database.</em></p>
<p>You want to create dummy entries in your Rails app, either for testing, for development, or for production, to make your site appear popular. Whatever the reason, populating your database can be done easily using fixtures.</p>
<p>While rake/fixtures/migrations can get a lot more complex, this will be a brief introductory example.</p>
<h1>Initial App setup</h1>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ rails characters
$ <span style="color: #7a0874; font-weight: bold;">cd</span> characters<span style="color: #000000; font-weight: bold;">/</span></pre></div></div>

<p>Edit config/database.yml &#8211; We only need a development database. So open up PHPMyAdmin or the MySQL command shell and:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">mysql&amp;gt; <span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">DATABASE</span> characters_development;
Query OK<span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span> row affected <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0.00</span> sec<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p><em>(I&#8217;m assuming you&#8217;re using MySQL. You can use anything; SQLite, Postgres, etc..) </em></p>
<h3>Create a model and a table in the database (using a migration)</h3>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">$ script<span style="color:#006600; font-weight:bold;">/</span>generate model Character
      exists  app<span style="color:#006600; font-weight:bold;">/</span>models<span style="color:#006600; font-weight:bold;">/</span>
      exists  test<span style="color:#006600; font-weight:bold;">/</span>unit<span style="color:#006600; font-weight:bold;">/</span>
      exists  test<span style="color:#006600; font-weight:bold;">/</span>fixtures<span style="color:#006600; font-weight:bold;">/</span>
      create  app<span style="color:#006600; font-weight:bold;">/</span>models<span style="color:#006600; font-weight:bold;">/</span>character.<span style="color:#9900CC;">rb</span>
      ....
&nbsp;
$ vim db<span style="color:#006600; font-weight:bold;">/</span>migrate<span style="color:#006600; font-weight:bold;">/</span>001_create_characters.<span style="color:#9900CC;">rb</span></pre></div></div>

<p>Sexy migration:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> CreateCharacters <span style="color:#006600; font-weight:bold;">&amp;</span>lt; <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Migration</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">up</span>
    create_table <span style="color:#ff3333; font-weight:bold;">:characters</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>t<span style="color:#006600; font-weight:bold;">|</span>
      t.<span style="color:#9900CC;">string</span>  <span style="color:#ff3333; font-weight:bold;">:name</span>, <span style="color:#ff3333; font-weight:bold;">:alias</span>, <span style="color:#ff3333; font-weight:bold;">:motto</span>
      t.<span style="color:#9900CC;">timestamps</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">down</span>
    drop_table <span style="color:#ff3333; font-weight:bold;">:characters</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Now migrate development (default environment):</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ rake db:migrate</pre></div></div>

<h3>Create the characters fixture</h3>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">vim</span> test<span style="color: #000000; font-weight: bold;">/</span>fixtures<span style="color: #000000; font-weight: bold;">/</span>characters.yml</pre></div></div>

<p><span id="more-85"></span><br />
This is a <a href="http://en.wikipedia.org/wiki/YAML">YAML</a> file. It is easy to read and easy to edit. <em>(One may also use the CSV format, extension .csv).</em></p>
<p>Some notes:</p>
<ul>
<li>Each model has a corresponding fixture file with the same name in the <strong>test/fixtures/</strong> path in your app&#8217;s root directory.</li>
<li>Each &#8216;fixture&#8217; is a record in the database table, and consists of a label, and then values for each field (i.e., name, age, etc..).</li>
<li>Optional fields can be skipped. They will default to either NULL, or their default value set in the database.</li>
<li>The id doesn&#8217;t need to be specified. It will be auto-incremented automatically, but be careful of conflicts if you&#8217;re specifying the ID for some fixtures and not others.</li>
<li>Whitespace matters. Make it purty.</li>
<li>You may embed Ruby code in the fixture file, in both the YAML and CSV fixture formats. (i.e., &lt;% f() -%&gt; or created_at: &lt;%= Time.now %&gt;)</li>
<li>To load fixtures, you use <strong>rake db:fixtures:load</strong>. This loads the fixtures into your current environment (can be set via RAILS_ENV shell var or in config/environment.rb).<em>One thing that might be confusing is the fact that fixtures reside in test/. Many people believe that fixtures can only be used in the test environment, but this is not the case. </em></li>
<li>When a fixture are loaded, any data previously in the table will be wiped out. You don&#8217;t need to fear altering or losing your test data when testing (i.e., destroy methods, &#8230;), just reload the fixtures. In the test environment, fixtures may be loaded before each test case is run by using the fixtures method (fixtures :employees, :orders, &#8230;). Keep in mind that you&#8217;re using a freshly loaded fixtures between every case method (if you&#8217;re loading).</li>
</ul>
<p>This is what our fixture file should look like. I will dissect it below:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">riddler:
  name: Edward Nashton
  alias: Riddler
  motto: Riddle me this, riddle me that
&nbsp;
pp:
  name: Peter Parker
  alias: Spiderman
  motto: One for JJ
  created_at: &amp;lt;%= Time.now %&amp;gt;
  updated_at: &amp;lt;%= Time.now %&amp;gt;
&nbsp;
JILL:
  id: 101
  name: Jill Valentine
  motto: Im a member of S*T*A*R*S
&nbsp;
dan_forden:
  name: Dan Forden
  motto: Toasty!
&nbsp;
hotness:
  name: Sorceress
  motto: Time is mana
&nbsp;
Airplane:
  name: Steve McCroskey
  motto: Looks like I picked the wrong week to quit sniffing glue.</pre></div></div>

<p>Let&#8217;s examine the first fixture:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">riddler:
  name: Edward Nashton
  alias: Riddler
  motto: Riddle me this, riddle me that</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">riddler:</pre></div></div>

<p>This is a name for the fixture. It begins at the beginning of the line, and it doesn&#8217;t matter what you call it. That information is not saved in the database and you might never use it. Ideally, names should be descriptive. You may also just go generic, &#8220;person1, person2, person3&#8243; etc.</p>
<p>When using the CSV format, fixture names are generated automatically and are in this format:</p>
<pre>model_name-counter</pre>
<p>In our example above, our fixtures would be named character-1, character-2, etc.</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">  name: Edward Nashton
  alias: Riddler
  motto: Riddle me this, riddle me that</pre></div></div>

<p>These three are the values this fixture (record) will have in the database. They go under the fixture name, tabbed or spaced evenly. When going on to the next fixture, just leave a blank line.</p>
<p>The above is like doing this:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&amp;</span>gt;<span style="color:#006600; font-weight:bold;">&amp;</span>gt; r = Character.<span style="color:#5A0A0A; font-weight:bold;">new</span>
<span style="color:#006600; font-weight:bold;">&amp;</span>gt;<span style="color:#006600; font-weight:bold;">&amp;</span>gt; r.<span style="color:#9900CC;">name</span> = <span style="color:#996600;">'Edward Nashton'</span>
<span style="color:#006600; font-weight:bold;">&amp;</span>gt;<span style="color:#006600; font-weight:bold;">&amp;</span>gt; r.<span style="color:#9966CC; font-weight:bold;">alias</span> = <span style="color:#996600;">'Riddler'</span>
<span style="color:#006600; font-weight:bold;">&amp;</span>gt;<span style="color:#006600; font-weight:bold;">&amp;</span>gt; r.<span style="color:#9900CC;">motto</span> = <span style="color:#996600;">'Riddle me this, riddle me that'</span>
<span style="color:#006600; font-weight:bold;">&amp;</span>gt;<span style="color:#006600; font-weight:bold;">&amp;</span>gt; r.<span style="color:#5A0A0A; font-weight:bold;">save</span></pre></div></div>

<p>id, created_at and updated_at are optional, but may be specified. Keep in mind that this file is going to be preprocessed with Ruby, so you may embed Ruby code (ERb) anywhere in the file.</p>
<h3>Load Fixture into Development Database</h3>
<p>This loads fixtures into the current RAILS_ENV, which, by default, is development.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ rake db:fixtures:load</pre></div></div>

<p>If you check your database now, you will find the fixtures you just loaded residing in the specific table. Let&#8217;s poke at this table in the Rails console.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ script<span style="color: #000000; font-weight: bold;">/</span>console
<span style="color: #000000; font-weight: bold;">&amp;</span>gt;<span style="color: #000000; font-weight: bold;">&amp;</span>gt; them = Character.find<span style="color: #7a0874; font-weight: bold;">&#40;</span>:all<span style="color: #7a0874; font-weight: bold;">&#41;</span>
=<span style="color: #000000; font-weight: bold;">&amp;</span>gt; <span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #666666; font-style: italic;">#&amp;gt; them[0].name</span>
=<span style="color: #000000; font-weight: bold;">&amp;</span>gt; Edward Nashton
&nbsp;
<span style="color: #000000; font-weight: bold;">&amp;</span>gt;<span style="color: #000000; font-weight: bold;">&amp;</span>gt; them<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">0</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>.alias
=<span style="color: #000000; font-weight: bold;">&amp;</span>gt; Riddler
&nbsp;
<span style="color: #000000; font-weight: bold;">&amp;</span>gt;<span style="color: #000000; font-weight: bold;">&amp;</span>gt; them<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">0</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>.motto
=<span style="color: #000000; font-weight: bold;">&amp;</span>gt; Riddle me this, riddle me that</pre></div></div>

<p>See these links for more info:</p>
<h1>External links</h1>
<ul>
<li><a href="http://www.ryandaigle.com/articles/2007/10/26/what-s-new-in-edge-rails-fixtures-just-got-a-whole-lot-easier" target="_blank">Fixtures Just Got a Whole Lot Easier</a></li>
<li><a href="http://techpolesen.blogspot.com/2007/04/rails-fixture-tips.html" target="_blank">Rails Fixture Tips</a></li>
<li><a href="http://manuals.rubyonrails.com/read/chapter/26" target="_blank">The Lo-Down on Fixtures </a></li>
<li><a href="http://railscasts.com/episodes/81" target="_blank">Fixtures in Rails 2.0</a></li>
<li><a href="http://oomoo.wordpress.com/2008/03/11/migration-related-rake-commands/" target="_blank">Migration Related Rake Commands (Rake Cheatsheet)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://biodegradablegeek.com/2008/07/how-to-use-fixtures-to-populate-your-database-in-rails/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Simple Way to Populate a Database in Rails</title>
		<link>http://biodegradablegeek.com/2008/03/simple-way-to-populate-a-database-in-rails/</link>
		<comments>http://biodegradablegeek.com/2008/03/simple-way-to-populate-a-database-in-rails/#comments</comments>
		<pubDate>Wed, 19 Mar 2008 01:23:31 +0000</pubDate>
		<dc:creator>Isam</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://biodegradablegeek.com/2008/03/18/simple-way-to-populate-a-database-in-rails/</guid>
		<description><![CDATA[This is how I populate my database when I have a lot of data but can&#8217;t be bothered to write more than a quick throw-away hack. This doesn&#8217;t use fixtures, nor migrations (nothing wrong with them, I wuv migrations). Just a ruby file and the Rails console (this is optional actually).
I create a new rb [...]]]></description>
			<content:encoded><![CDATA[<p>This is how I populate my database when I have a lot of data but can&#8217;t be bothered to write more than a quick throw-away hack. This doesn&#8217;t use fixtures, nor migrations (nothing wrong with them, I wuv migrations). Just a ruby file and the Rails console (this is optional actually).</p>
<p>I create a new rb file in lib/ (you can put your files in a sub-directory or anywhere &#8216;load&#8217; can find them), then write the data I want inserted into the database in a new function in that file. I do so exactly as I would insert data in Rails. Model.create, Model.new, etc&#8230;</p>
<p>I then get into the Rails console (<em>ruby script/console</em>) and do <em>load &#8216;file.rb&#8217;</em> and simply call the function. The database used will vary according to the environment you&#8217;re in (test, development, etc). Using &#8216;load&#8217; every time you call your function(s) is preferred. Load will keep reloading the file (as opposed to &#8216;require&#8217; which only reads a file once), staying up to date with edits you&#8217;re making to the file. For example, in the console:</p>
<p><em>&gt;&gt; load &#8216;funk.rb&#8217;; add_default_settings</em></p>
<p><em>(funk.rb is in /lib/ and add_default_settings is a function in that file) </em></p>
<p>As of 2.x, Rails now has rake db:migrate:reset and db:migrate:redo, which sends you down one migration and then back up to the current migration (or you can decide how many hops to take back using STEP=n). This is great, especially for tasks like populating a database.</p>
<p>So why don&#8217;t I use migrations? I do, but sometimes, especially in a proof-of-concept or throw-away app, I find it faster to skip the proper methods and write up  a quick function. If you think that&#8217;s bad, you should see my lingering Python addiction. Sometimes I catch myself metaprogramming Ruby code in Python.</p>
]]></content:encoded>
			<wfw:commentRss>http://biodegradablegeek.com/2008/03/simple-way-to-populate-a-database-in-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Understanding Basic Database Relationships in Rails</title>
		<link>http://biodegradablegeek.com/2007/12/understanding-basic-database-relationships-in-rails/</link>
		<comments>http://biodegradablegeek.com/2007/12/understanding-basic-database-relationships-in-rails/#comments</comments>
		<pubDate>Thu, 27 Dec 2007 02:01:15 +0000</pubDate>
		<dc:creator>Isam</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[database relationships]]></category>
		<category><![CDATA[migrations]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://biodegradablegeek.com/2007/12/26/understanding-basic-database-relationships-in-rails/</guid>
		<description><![CDATA[
This short tutorial will be beneficial for you if database relationships and keywords like belongs_to and has_many confuse you, or if you&#8217;re trying to find out how relationships are implemented in Rails. As we create a small demonstration project, you&#8217;ll see that one beauty of Rails is how it does most of the work gluing [...]]]></description>
			<content:encoded><![CDATA[<p><img src='/wp-content/uploads/2007/12/keke_nixon_erd.jpg' alt='Nixon ERD' align="left" title="Understanding Basic Database Relationships in Rails" /></p>
<p>This <i>short</i> tutorial will be beneficial for you if database relationships and keywords like belongs_to and has_many confuse you, or if you&#8217;re trying to find out how relationships are implemented in Rails. As we create a small demonstration project, you&#8217;ll see that one beauty of Rails is how it does most of the work gluing everything together, after you&#8217;ve supplied it with information about your database&#8217;s structure.</p>
<p>But first &#8212; why bother learning about relationships? Very simply, they eliminate a major problem called an update anomaly, and they will probably save you disk space. Having info repeated in multiple entries can be problematic. How would you update a mass misspelling? Would you even notice a misspelled entry? <a href="http://en.wikipedia.org/wiki/Database_normalization">Database normalization</a> and multiple intertwined tables (via relationships) can curb this problem. Fortunately, ActiveRecord makes this easy.</p>
<p>For example, if you store the name and location of all your users in the same database table, you might be wasting disk space by having the same information repeated in multiple entries. You would be wasting a lot of space if your clam-cake-vendor-review site has hundreds of users living in &#8220;the State of Rhode Island and Providence Plantations.&#8221; This can be eliminated by having the locations tied to unique IDs in their own table, and associated to a user by their ID. This also makes renaming a location easy. Changing &#8220;the State of Rhode Island and Providence Plantations&#8221; to &#8220;Ocean State&#8221; is only done in one location, once.</p>
<p>Rather than going over all possible types of relationships here, I will be covering the very basics; Enough to help you grasp the main idea and see how it is implemented in Rails. Let&#8217;s begin by designing a simple project.<br />
<span id="more-44"></span></p>
<h3>Project Description</h3>
<p>Let&#8217;s design a basic musician database. Each artist will be one individual with a name, age, and list of songs (not albums). Each song will have a title, duration and fit under one genre. This design is overly simplified and far from realistic. For simplicity&#8217;s sake, we are ignoring the fact that an artist may consist of several individuals and may have multiple albums containing multiple songs, and each song, artist and album can fit under a mesh of genres. It might have a tough time competing with MusicBrainz or Last.fm, but it should be sufficient enough for our purpose.</p>
<h2>Go Go Go</h2>
<p>Ruby on Rails and your database software (I use MySQL, but SQLite/PostgreSQL work fine) should be installed and functional. For help installing Rails, see <a href="http://www.rubyonrails.org/down">the official site</a> and <a href="http://wiki.rubyonrails.org/rails/pages/GettingStartedWithRails">the official Wiki</a>.</p>
<p><i>(If using an editor such as <a href="/2007/12/13/using-vim-as-a-complete-ruby-on-rails-ide/">vim with rails.vim</a>, you may substitute those commands and shortcuts for the console commands I use here)</i></p>
<p>In the directory you want your project to reside, create a Rails framework named themusic:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">$ rails themusic
    create
    create app<span style="color: #000000; font-weight: bold;">/</span>controllers
    create app<span style="color: #000000; font-weight: bold;">/</span>helpers
    create app<span style="color: #000000; font-weight: bold;">/</span>models
    create app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>layouts
    create app<span style="color: #000000; font-weight: bold;">/</span>environments
    ... omitted ...</pre></td></tr></table></div>

<p>Head into the newly created <i>themusic</i> directory and open config/database.yml using your <a href="http://www.vim.org">favorite text editor</a>. This file tells Rails what database software you&#8217;re using and how it can access it. Notice that this file is divided into three parts (environments): Development, test and production. Rails has the ability to use different databases and even database software for each environment. We will stick in the development environment.</p>
<p>In development, any changes you make to the code are immediate &#8211; not requiring a server restart to take effect &#8211; and errors spit out a detailed stack trace. The trade off? Performance takes a hit.</p>
<p>Fill in your database login information (you&#8217;ll likely just have to put in your password) before saving and closing the file. Create a new database named themusic_development. I use <a href="http://phpmyadmin.net">PHPMyAdmin</a>, but this can be done in MySQL using the commandline:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">&lt;pre&gt;
$ mysql -u username -h localhost -p
Enter password: (type pass and hit Enter)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1984
&nbsp;
mysql&gt; CREATE DATABASE themusic_development;
Query OK, 1 row affected (0.04 sec)</pre></td></tr></table></div>

</pre>
<h2>Identifying Entities and Attributes</h2>
<p>An entity is any object you are required to keep information on. Examples of entities include customers, orders, departments and items. How many entities are we keeping track of in our example app? Three: Artist, song and genre. Keep in mind that things you don't need to store data on are not entities. If your business doesn't require that you keep track of user or customer information, then they don't have to be entities. Identifying entities isn't always straightforward, and it's not uncommon to alter your app after the initial design phase, so don't sweat this too much right now; Just follow along.</p>
<p>Each entity has attributes. A person entity might have attributes such as name and DOB. If we were writing a stock inventory system, each item entity might have a price, manufacturer, description, and so forth. In our example, we have the following entities and attributes:</p>
<ul>
<li>Artist: Has a name, age and songs.</li>
<li>Song: Has a title, duration and fits under one artist and one genre.</li>
<li>Genre: Each has a name, and houses many songs.</li>
</ul>
<p>Here's an aesthetic entity-relationship diagram (ERD) depicting this. A crow's foot line is a "has_many" relationship. (You can read it going in both directions as: An artist has many songs, a song belongs to an artist):<br />
<img src='http://biodegradablegeek.com/wp-content/uploads/2007/12/erd_understanding_relationships1.gif' alt='ERD depicting basic DB relationship' title="Understanding Basic Database Relationships in Rails" /><br />
Also note sexy 60's font.</p>
<h2>Generating the Models and Setting Up the Migrations and Relationships</h2>
<p>We have defined our entities and their relationships on paper, and now need them implemented in Rails. Let's generate three models representing our entities:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">$ ruby script<span style="color: #000000; font-weight: bold;">/</span>generate model Artist
$ ruby script<span style="color: #000000; font-weight: bold;">/</span>generate model Song
$ ruby script<span style="color: #000000; font-weight: bold;">/</span>generate model Genre</pre></td></tr></table></div>

<p>The generate script automatically creates a migration for each model.</p>
<p>Migrations are optional but immensely helpful (and awesome). If you have no clue what I'm talking about, see <a  href="http://wiki.rubyonrails.org/rails/pages/UnderstandingMigrations">UnderstandingMigrations</a> and <a  href="http://glu.ttono.us/articles/2005/10/27/the-joy-of-migrations">the joy of migrations</a>.</p>
<p>Let's edit each migration to create the appropriate fields for each table.</p>
<p><i>(Although not advised, you may use the MySQL console to create the tables and columns instead of using migrations and rake)</i></p>
<h3>Table structure</h3>
<p>The artist table will have the following fields:</p>
<ul>
<li>Unique ID: Created automatically by Rails; We don't need this in the migration file.</li>
<li>Name: a string</li>
<li>Age: a small integer</li>
</ul>
<p>Open up the Artist model's migration file (db/migrate/001_create_artists.rb) and edit it to resemble this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> CreateArtists <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Migration</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">up</span>
    create_table <span style="color:#ff3333; font-weight:bold;">:artists</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>t<span style="color:#006600; font-weight:bold;">|</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:name</span>, <span style="color:#ff3333; font-weight:bold;">:string</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:age</span>, <span style="color:#ff3333; font-weight:bold;">:integer</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">down</span>
    drop_table <span style="color:#ff3333; font-weight:bold;">:artists</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>The song table will have the following fields:</p>
<ul>
<li>Title: a string</li>
<li>Duration in seconds: an integer</li>
<li>Artist: Identified by the artist's unique ID (integer and cannot be NULL)</li>
<li>Genre: Identified by the genre's unique ID (as above, a NON-NULL integer)</li>
</ul>
<p>Edit the Song migration (db/migrate/002_create_songs.rb):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> CreateSongs <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Migration</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">up</span>
    create_table <span style="color:#ff3333; font-weight:bold;">:songs</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>t<span style="color:#006600; font-weight:bold;">|</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:title</span>, <span style="color:#ff3333; font-weight:bold;">:string</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:duration</span>, <span style="color:#ff3333; font-weight:bold;">:integer</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:artist_id</span>, <span style="color:#ff3333; font-weight:bold;">:integer</span>, <span style="color:#ff3333; font-weight:bold;">:null</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">false</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:genre_id</span>, <span style="color:#ff3333; font-weight:bold;">:integer</span>, <span style="color:#ff3333; font-weight:bold;">:null</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">false</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">down</span>
    drop_table <span style="color:#ff3333; font-weight:bold;">:songs</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>The genre table will have a name field. Edit that migration (db/migrations/003_create_genres.rb):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> CreateGenres <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Migration</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">up</span>
    create_table <span style="color:#ff3333; font-weight:bold;">:genres</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>t<span style="color:#006600; font-weight:bold;">|</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:name</span>, <span style="color:#ff3333; font-weight:bold;">:string</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">down</span>
    drop_table <span style="color:#ff3333; font-weight:bold;">:genres</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Use Rake to apply the migrations to your database. If all goes well, your console should display something like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">$ rake db:migrate
<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>lotus<span style="color: #000000; font-weight: bold;">/</span>rails<span style="color: #000000; font-weight: bold;">/</span>themusic<span style="color: #7a0874; font-weight: bold;">&#41;</span>
== CreateArtists: migrating ====================
<span style="color: #660033;">--</span> create_table<span style="color: #7a0874; font-weight: bold;">&#40;</span>:artists<span style="color: #7a0874; font-weight: bold;">&#41;</span>
   -<span style="color: #000000; font-weight: bold;">&gt;</span> 0.0896s
== CreateArtists: migrated <span style="color: #7a0874; font-weight: bold;">&#40;</span>0.0897s<span style="color: #7a0874; font-weight: bold;">&#41;</span> ==============
&nbsp;
== CreateSongs: migrating ======================
<span style="color: #660033;">--</span> create_table<span style="color: #7a0874; font-weight: bold;">&#40;</span>:songs<span style="color: #7a0874; font-weight: bold;">&#41;</span>
   -<span style="color: #000000; font-weight: bold;">&gt;</span> 0.0263s
== CreateSongs: migrated <span style="color: #7a0874; font-weight: bold;">&#40;</span>0.0264s<span style="color: #7a0874; font-weight: bold;">&#41;</span> ================
&nbsp;
== CreateGenres: migrating =================
<span style="color: #660033;">--</span> create_table<span style="color: #7a0874; font-weight: bold;">&#40;</span>:genres<span style="color: #7a0874; font-weight: bold;">&#41;</span>
   -<span style="color: #000000; font-weight: bold;">&gt;</span> 0.0350s
== CreateGenres: migrated <span style="color: #7a0874; font-weight: bold;">&#40;</span>0.0351s<span style="color: #7a0874; font-weight: bold;">&#41;</span> ===========</pre></td></tr></table></div>

<h3>Relationships</h3>
<p>Rails needs to know how your models are related. We already did this in the design phase earlier above, but we now need to translate it into terms Rails can understand. Each artist will have multiple songs; Rails understands this using the keyword <i>has_many</i>. Edit the artist model (app/models/artist.rb) to look like this (notice that :songs is plural):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Artist <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  <span style="color:#5A0A0A; font-weight:bold;">has_many</span> <span style="color:#ff3333; font-weight:bold;">:songs</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>This association is pretty self-explanatory when spoken aloud: Artist has many Songs.</p>
<p>Each song will belong to one artist and one genre. In the migration, we specifically defined that artist_id and genre_id must exist, they cannot not be NULL. This means a song <strong>must</strong> belong to an artist <i>and</i> fit under a genre.</p>
<p>Edit song.rb (notice both params supplied to belongs_to are singular):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Song <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  <span style="color:#5A0A0A; font-weight:bold;">belongs_to</span> <span style="color:#ff3333; font-weight:bold;">:artist</span>
  <span style="color:#5A0A0A; font-weight:bold;">belongs_to</span> <span style="color:#ff3333; font-weight:bold;">:genre</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>We can have multiple songs under the same genre. This is a has_many association. Add it to genre.rb:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Genre <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  <span style="color:#5A0A0A; font-weight:bold;">has_many</span> <span style="color:#ff3333; font-weight:bold;">:songs</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<h2>Interacting with Our App Via Console</h2>
<p>Instead of creating a web interface or editing scaffolds, let's use the Rails console to interact with our application in its current state. The Rails console is a script named 'console' in our apps' script directory. This console gives you low level access to your Ruby on Rails application, which it loads on its own. It's a powerful debugger, and makes it fast and easy to test out individual components in your program -- not to mention it's fun! It isn't always practical but suffices perfectly for our purposes now.</p>
<p>Fire it up: ruby script/console.  You should get a >> prompt.</p>
<p>The console includes tab-completion (for example, press Artist.f<tab><tab> for a list of commands beginning with the letter f), so feel free to poke around and experiment.</p>
<p>Let's begin by creating an instance of the Artist model. Type the following and hit enter.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb = Artist.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Joe Bloggs'</span>, <span style="color:#ff3333; font-weight:bold;">:age</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">36</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></td></tr></table></div>

<p>We have essentially created a new record in our database, but if you check your artist's table in the database now, you'll notice that this entry is non-existent. This is because it only exists in memory at this point. We have not saved it. It doesn't have a unique ID associated with it. The <i>new_record?</i> method returns true if the model has never been saved. You can access an object's methods and attributes via the console:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#9900CC;">new_record</span>?
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#9900CC;">name</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Joe Bloggs&quot;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#9900CC;">age</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">36</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#9900CC;">id</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">nil</span></pre></td></tr></table></div>

<p>Now try this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#9900CC;">songs</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span></pre></td></tr></table></div>

<p>WTFMATEOMGMAGIC! []!? An empty array? Do you remember adding a songs attribute? I hope not, 'cause you didn't! Rails knows that an Artist object can have multiple songs because you defined this association in the Artist model as 'has_many :songs.' Each song the artist has will be added to this array.</p>
<p>Notice that the record gets an ID after it is saved:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#5A0A0A; font-weight:bold;">save</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#9900CC;">id</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">1</span></pre></td></tr></table></div>

<p>Save returns <i>true</i> on success. Let's create a Song instance:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> tune = Song.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:title</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Love Me Three Times'</span>, <span style="color:#ff3333; font-weight:bold;">:duration</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">456</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#008000; font-style:italic;">#&lt;song:0x2b420d56ec00 @attributes={&quot;artist_id&quot;=&gt;nil, &quot;title&quot;=&gt;&quot;Love Me Three Times&quot;, &quot;genre_id&quot;=&gt;nil, &quot;duration&quot;=&gt;456}, @new_record=true&gt;</span></pre></td></tr></table></div>

<p>Trying to save our song as this point gives us errors:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> tune.<span style="color:#5A0A0A; font-weight:bold;">save</span>
<span style="color:#6666ff; font-weight:bold;">ActiveRecord::StatementInvalid</span>: <span style="color:#6666ff; font-weight:bold;">Mysql::Error</span>: Column <span style="color:#996600;">'artist_id'</span> cannot be null:
... <span style="color:#9900CC;">long</span> trace omitted ...</pre></td></tr></table></div>

<p>Remember that artist_id and genre_id cannot be left nil. Let's create some genres on the fly. In practice, this should be done in a migration.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> Genre.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Bluegrass'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#5A0A0A; font-weight:bold;">save</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> Genre.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Goa Trance'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#5A0A0A; font-weight:bold;">save</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> Genre.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Doo Wop'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#5A0A0A; font-weight:bold;">save</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> Genre.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Blues Rock'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#5A0A0A; font-weight:bold;">save</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> Genre.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Emo'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#5A0A0A; font-weight:bold;">save</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span></pre></td></tr></table></div>

<p>Assign the tune a genre:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> tune.<span style="color:#9900CC;">genre</span> = Genre.<span style="color:#9900CC;">find_by_name</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'Blues Rock'</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></td></tr></table></div>

<p>See that it has been set (don't worry if your ID differs):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> tune.<span style="color:#9900CC;">genre</span>.<span style="color:#9900CC;">name</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Blues Rock&quot;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> tune.<span style="color:#9900CC;">genre_id</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">4</span></pre></td></tr></table></div>

<p>Use the Array object's << operand to append to Joe Blogg's song array and then save it.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#9900CC;">songs</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> tune
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> tune.<span style="color:#5A0A0A; font-weight:bold;">save</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span></pre></td></tr></table></div>

<p>Exploration:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> jb.<span style="color:#9900CC;">songs</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">title</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Love Me Three Times&quot;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> tune.<span style="color:#9900CC;">artist</span>.<span style="color:#9900CC;">name</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Joe Bloggs&quot;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> tune.<span style="color:#9900CC;">artist_id</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">1</span></pre></td></tr></table></div>

<p>Let's fetch and create an instance of Joe Blogg's record from the database:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> bloggs = Artist.<span style="color:#9900CC;">find_by_name</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'Joe Bloggs'</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></td></tr></table></div>

<p>Let's explore this object further:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> bloggs.<span style="color:#9900CC;">name</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Joe Bloggs&quot;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> bloggs.<span style="color:#9900CC;">songs</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">title</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Love Me Three Times&quot;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> bloggs.<span style="color:#9900CC;">songs</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">genre</span>.<span style="color:#9900CC;">name</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Blues Rock&quot;</span></pre></td></tr></table></div>

<p>Add a few more artists and songs to the database and then close the console (ctrl+D or type "quit").</p>
<p>In the Songs table in our database, the genre and artist are stored by ID as opposed to by string. Even if we have a centillion songs by one artist, updating that artist's info is only done in one place, once - in the record associated with that ID. If Joe Bloggs changes his name to "The Artist Formerly Known As Joe Bloggs," we only need to change this once, and it will take effect throughout our app.</p>
<h2>Creating a Browser Interface</h2>
<p>Don't get stoned (on beer) just yet. You have a basic understanding of why relationships are useful and how they work, but it's unlikely your application will be restricted to the Rails console. Let's create a very basic (and hideous) web interface for our music application. Each objective will be followed by details and caveats on its implementation.</p>
<p>We have models, but we also need controllers and views. Controllers handle events from the user, fetch data from models, and generate the output (view) that our users will see and interact with. This is known as the <a href="http://en.wikipedia.org/wiki/Model-view-controller">MVC architecture</a>.</p>
<p>By convention, a controller's name is plural as opposed to a model which is singular. For example: StoriesController, PicturesController, PeopleController, etcetra; Rails adds the 'Controller' suffix to the name you give the generate script. Memorizing Rails' naming conventions can be confusing at first. I advise keeping the <a href="http://nubyonrails.com/tools/pluralize/">excellent pluralize tool</a> on hand.</p>
<h3>Objective #1</h3>
<p>When the user visits http://domain.cxm/artists, we want them greeted with a list of the artists in our database. Clicking an artist's name will open a page with that artist's personal info and list of songs.</p>
<p>Use the following code to generate the first controller:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">$ ruby script<span style="color: #000000; font-weight: bold;">/</span>generate controller Artists</pre></td></tr></table></div>

<p>The index view (what the user will see) needs to have a list of artists from the database. Add the following index method to the new controller in app/controllers/artists_controller.rb:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> ArtistsController <span style="color:#006600; font-weight:bold;">&lt;</span> ApplicationController
    <span style="color:#9966CC; font-weight:bold;">def</span> index
        <span style="color:#0066ff; font-weight:bold;">@artists</span> = Artist.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:all</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>find(:all) returns all the records in the Artists table. Create the view file app/views/artists/index.rhtml and add the following to it:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">&lt;h1&gt;The Music Just Turns Me On&lt;/h1&gt;
&lt;h2&gt;Available artists&lt;/h2&gt;
&lt;ul&gt;
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#0066ff; font-weight:bold;">@artists</span>.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>artist<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    &lt;li&gt;<span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#5A0A0A; font-weight:bold;">link_to</span> artist.<span style="color:#9900CC;">name</span>, <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'details'</span>, <span style="color:#ff3333; font-weight:bold;">:id</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> artist.<span style="color:#9900CC;">id</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>&lt;/li&gt;
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&lt;/ul&gt;</pre></td></tr></table></div>

<p>Fire up the server script ($ ruby script/server) and point your browser to <a href="http://localhost:3000/artists" target="_blank">http://localhost:3000/artists</a>. This is the default address for a rails application. If all is well with the world, you'll see this in your browser:</p>
<h1 style="color:black;">The Music Just Turns Me On</h1>
<h2 style="color:black;">Available artists</h2>
<ul>
<li><a href="http://localhost:3000/artists/details/1" target="_blank">Joe Bloggs</a></li>
</ul>
<p>In my example I only have one artist; More would better illustrate the code, particularly later below. Clicking on an artist's name will lead to an "Unknown action" error, as we do not yet have a <i>details</i> method in our ArtistsController. Let's add that to our controller now:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> details
    <span style="color:#0066ff; font-weight:bold;">@artist</span> = Artist.<span style="color:#9900CC;">find_by_id</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:id</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@songs</span> = <span style="color:#0066ff; font-weight:bold;">@artist</span>.<span style="color:#9900CC;">songs</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>The details.rhtml view (create it in the same dir as the index view) should look like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">&lt;h1&gt;<span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#0066ff; font-weight:bold;">@artist</span>.<span style="color:#9900CC;">name</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> (<span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#0066ff; font-weight:bold;">@artist</span>.<span style="color:#9900CC;">age</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>)&lt;/h1&gt;
&lt;ol&gt;
    <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#0066ff; font-weight:bold;">@songs</span>.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>song<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
        &lt;li&gt;<span style="color:#006600; font-weight:bold;">&lt;%</span>= song.<span style="color:#9900CC;">title</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> <span style="color:#006600; font-weight:bold;">&lt;%</span>= song.<span style="color:#9900CC;">duration</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> -- <span style="color:#006600; font-weight:bold;">&lt;%</span>= song.<span style="color:#9900CC;">genre</span>.<span style="color:#9900CC;">name</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>&lt;/li&gt;
    <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&lt;/ol&gt;</pre></td></tr></table></div>

<p>Refresh (or run the server again if you closed it) and click an artist's name in your browser to see the details view:</p>
<h3 style="color:black;">Joe bloggs (36)</h3>
<ol>
<li>Love Me Three Times 456 -- Blues Rock</li>
</ol>
<p>456 is the duration in seconds; Appropriate for storage, but will bring us terrible misfortune from the marketing department. Let's make it user-friendly in the form of minutes:seconds. Change the songs.each loop above to the following:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">&lt;ol&gt;
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#0066ff; font-weight:bold;">@songs</span>.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>song<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    <span style="color:#006600; font-weight:bold;">&lt;%</span>
        min = song.<span style="color:#9900CC;">duration</span> <span style="color:#006600; font-weight:bold;">/</span> <span style="color:#006666;">60</span>
        sec = song.<span style="color:#9900CC;">duration</span> <span style="color:#006600; font-weight:bold;">%</span> <span style="color:#006666;">60</span>
        <span style="color:#0066ff; font-weight:bold;">@duration</span> = <span style="color:#996600;">'%d:%.2d'</span> <span style="color:#006600; font-weight:bold;">%</span> <span style="color:#006600; font-weight:bold;">&#91;</span>min, sec<span style="color:#006600; font-weight:bold;">&#93;</span>
    <span style="color:#006600; font-weight:bold;">%&gt;</span>
    &lt;li&gt;<span style="color:#006600; font-weight:bold;">&lt;%</span>= song.<span style="color:#9900CC;">title</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> <span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#0066ff; font-weight:bold;">@duration</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> -- <span style="color:#006600; font-weight:bold;">&lt;%</span>= song.<span style="color:#9900CC;">genre</span>.<span style="color:#9900CC;">name</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>&lt;/li&gt;
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&lt;/ol&gt;</pre></td></tr></table></div>

<p>Check it in your browser:</p>
<h3 style="color:black;">Joe bloggs (36)</h3>
<ol>
<li>Love Me Three Times 7:36 -- Blues Rock</li>
</ol>
<p>Purty!</p>
<h3>Objective #2</h3>
<p>Users should be able to browse via genre. Clicking 'Blues Rock' should list every Blues Rock song from every artist in the database; Let's make this happen.</p>
<p>First, we will make the song genres on the Artist details page links leading to a method called 'browse' in a not-yet-existent genres controller.</p>
<p>In details.rhtml, change the &gt;li&lt; ... &gt;/li&lt; line to reflect the following:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">&lt;li&gt;<span style="color:#006600; font-weight:bold;">&lt;%</span>= song.<span style="color:#9900CC;">title</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> <span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#0066ff; font-weight:bold;">@duration</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> --
        <span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#5A0A0A; font-weight:bold;">link_to</span> song.<span style="color:#9900CC;">genre</span>.<span style="color:#9900CC;">name</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'genres'</span>, <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'browse'</span>, <span style="color:#ff3333; font-weight:bold;">:id</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> song.<span style="color:#9900CC;">genre</span>.<span style="color:#9900CC;">id</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>&lt;/li&gt;</pre></td></tr></table></div>

<p>Let's generate that controller and implement two methods.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">$ ruby script<span style="color: #000000; font-weight: bold;">/</span>generate controller Genres index browse</pre></td></tr></table></div>

<p>Open app/controllers/genres_controller.rb. We have two method skeletons: index and browse. To the browse method's body, we want to add code that does this:</p>
<p>Psuedo-code:</p>
<pre>

a3dc31606a42206c5c45a0962bb075c0101
</pre>
<p>Here's the Ruby code, add it to the controller:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">if</span> params.<span style="color:#9966CC; font-weight:bold;">include</span>? <span style="color:#ff3333; font-weight:bold;">:id</span>
    <span style="color:#0066ff; font-weight:bold;">@genre</span> = Genre.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:first</span>, <span style="color:#ff3333; font-weight:bold;">:conditions</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'id = ?'</span>, params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:id</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">else</span>
    <span style="color:#5A0A0A; font-weight:bold;">redirect_to</span> <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'index'</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>The find() returns the first (and only, as each genre should be unique) record matching the ID that was passed from the previous page. You can swap that find method with the simpler and easier to read Genre.find_by_id(params[:id]) if you wish.</p>
<p>Generate created an index view and a browse view for us because we passed it the method names when generating the GenresController. Open browse.rhtml, delete the placeholder HTML inside and add the following:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">&lt;h1&gt;Available <span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#0066ff; font-weight:bold;">@genre</span>.<span style="color:#9900CC;">name</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> songs&lt;/h1&gt;
&lt;ol&gt;
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#0066ff; font-weight:bold;">@genre</span>.<span style="color:#9900CC;">songs</span>.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>song<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    <span style="color:#006600; font-weight:bold;">&lt;%</span>
        min = song.<span style="color:#9900CC;">duration</span> <span style="color:#006600; font-weight:bold;">/</span> <span style="color:#006666;">60</span>
        sec = song.<span style="color:#9900CC;">duration</span> <span style="color:#006600; font-weight:bold;">%</span> <span style="color:#006666;">60</span>
        <span style="color:#0066ff; font-weight:bold;">@duration</span> = <span style="color:#996600;">'%d:%.2d'</span> <span style="color:#006600; font-weight:bold;">%</span> <span style="color:#006600; font-weight:bold;">&#91;</span>min, sec<span style="color:#006600; font-weight:bold;">&#93;</span>
    <span style="color:#006600; font-weight:bold;">%&gt;</span>
    &lt;li&gt;<span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#5A0A0A; font-weight:bold;">link_to</span> song.<span style="color:#9900CC;">artist</span>.<span style="color:#9900CC;">name</span>, <span style="color:#ff3333; font-weight:bold;">:controller</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'artists'</span>, <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'details'</span>, <span style="color:#ff3333; font-weight:bold;">:id</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> song.<span style="color:#9900CC;">artist</span>.<span style="color:#9900CC;">id</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> - <span style="color:#006600; font-weight:bold;">&lt;%</span>= song.<span style="color:#9900CC;">title</span> <span style="color:#006600; font-weight:bold;">%&gt;</span> (<span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#0066ff; font-weight:bold;">@duration</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>)&lt;/li&gt;
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&lt;/ol&gt;</pre></td></tr></table></div>

<p>Notice the blatant violation of Ruby on Rail's fundamental <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">Don't Repeat Yourself (DRY)</a> principle. Having the same code <a href="http://en.wikipedia.org/wiki/Cut_and_paste_programming">pasted</a> in more than one place is, among other things, sloppy programming. I only did this here because I don't want to violate the <a href="http://en.wikipedia.org/wiki/KISS_principle">KISS</a> principle. In your real apps, use partials, applications.rb and the application controller to maximize <a href="http://en.wikipedia.org/wiki/Code_reuse">Code Reuse</a>!</p>
<p>Point your browser to an artist's page and click a genre:</p>
<h1 style="color:black;">Available Blues Rock songs</h1>
<ol>
<li><a href="http://localhost:3000/artists/details/1" target="_blank">Joe Bloggs</a> - Love Me Three Times (7:36)</li>
</ol>
<p>The user should also be able to browse by all the available genres in the database. The app/views/genres/index.rhtml view (not to be confused with the ArtistController method's index view) needs a list of genres. Add the following code into the GenresController's index method:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#0066ff; font-weight:bold;">@genres</span> = Genre.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:all</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></td></tr></table></div>

<p>and the following in the genres/index.rhtml view (delete placeholder HTML, if any):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">&lt;h1&gt;Browse by genre&lt;/h1&gt;
&lt;ul&gt;
    <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#0066ff; font-weight:bold;">@genres</span>.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>cat<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
        &lt;li&gt;<span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#5A0A0A; font-weight:bold;">link_to</span> cat.<span style="color:#9900CC;">name</span>, <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:browse</span>, <span style="color:#ff3333; font-weight:bold;">:id</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> cat.<span style="color:#9900CC;">id</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>&lt;/li&gt;
    <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&lt;/ul&gt;</pre></td></tr></table></div>

<p>Hit up <a href="http://localhost:3000/genres/">http://localhost:3000/genres/</a>:</p>
<h1 style="color:black;">Browse by genre</h1>
<ul>
<li><a href="http://localhost:3000/genres/browse/1">Bluegrass</a></li>
<li><a href="http://localhost:3000/genres/browse/2">Goa Trance</a></li>
<li><a href="http://localhost:3000/genres/browse/3">Doo Wop</a></li>
<li><a href="http://localhost:3000/genres/browse/4">Blues Rock</a></li>
<li><a href="http://localhost:3000/genres/browse/5">Emo</a></li>
</ul>
<h3>Objective #3</h3>
<p>Give the user the ability to add artists and songs via forms.</p>
<p>Open app/views/artists/index.rhtml and add the following form_tag code right below the h1 header:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">&lt;!-- Form to add a new artist --&gt;
<span style="color:#006600; font-weight:bold;">&lt;%</span> form_tag <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:new</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    Name: <span style="color:#006600; font-weight:bold;">&lt;%</span>= text_field <span style="color:#ff3333; font-weight:bold;">:artist</span>, <span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    Age: <span style="color:#006600; font-weight:bold;">&lt;%</span>= text_field <span style="color:#ff3333; font-weight:bold;">:artist</span>, <span style="color:#ff3333; font-weight:bold;">:age</span>, <span style="color:#ff3333; font-weight:bold;">:size</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    <span style="color:#006600; font-weight:bold;">&lt;%</span>= submit_tag <span style="color:#996600;">'Add new artist'</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span></pre></td></tr></table></div>

<p>This snippet creates a form with three elements. A name textbox, an age textbox, and a submit button. ':action => :new' tells the form to direct the user's input to the ArtistController's <i>new</i> method. Open app/controllers/artists_controller.rb and add this <i>new</i> method now:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#5A0A0A; font-weight:bold;">new</span>
    <span style="color:#0066ff; font-weight:bold;">@newartist</span> = params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:artist</span><span style="color:#006600; font-weight:bold;">&#93;</span>
    Artist.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>@newartist<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#5A0A0A; font-weight:bold;">save</span>
    <span style="color:#5A0A0A; font-weight:bold;">redirect_to</span> <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:index</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Here's a brief overview of how this function works:</p>
<p><strong>Line 1: What is params[:artist]?</strong></p>
<p>I won't go over <a href="http://weblog.rubyonrails.org/2006/4/25/use-params-not-params">params</a> nor <a href="http://www.rubynoob.com/articles/2007/7/9/forms-in-ruby-on-rails_part_1">forms</a> too thoroughly here. Above in our view, we had "text_field :artist, :name" and "text_field :artist, :age" -- The first parameter we passed to both, ':artist,' is the object name. Rails generates a hash with that name and puts each input field's name (that's the second part we passed the two text_fields, ':name' and :'age' respectively) as a key in that hash. The value that key corresponds to is what the user inputed on the form. For example, if we have a form asking the user to tell us about his car:</p>
<ul>
<li>text_field :car, :model</li>
<li>text_field :car, :make</li>
<li>text_field :car, :year</li>
</ul>
<p>where the form's :action parameter points to method :vroom. In the vroom method, we'd have a hash named ':car' available in params (params[:car]). This hash will have three key-value pairs: params[:car][:model], params[:car][:make] and params[:car][:year]. The values of each will be whatever the user provided in the form's text fields.</p>
<p><strong>Line 2: Why are we passing params[:artist] to the Artist constructor (Artist.new)?</strong></p>
<p>We need to create a new Artist record in the database. We do so like this: Artist.new(:name => 'whatever', :age => 123). Artist.new accepts a hash with the keys :name and :age. @newartist is a hash with both those keys, because that's what we named our text_fields in the form above. It might be easier to understand knowing we can do this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">Artist.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@newartist</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:name</span><span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#ff3333; font-weight:bold;">:age</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@newartist</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:age</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>; Artist.<span style="color:#5A0A0A; font-weight:bold;">save</span></pre></td></tr></table></div>

<p>@newartist is optional. We can pass params[:artist] directly to Artist.new. In the real world you'd want to check ALL input coming from the user before any further processing.</p>
<p><strong>Line 3: Why are we redirecting to the index method?</strong></p>
<p>By default, Rails would have tried to give the user the new.rhtml view, resulting in an error (we don't have such a view). We override this behavior by redirecting flow to the index method. The index method runs its course and the user is then served the index.rhtml view. In practice, this means the user is taken to the front page after they click the submit button.</p>
<p>After the changes above, this is what the artist form should now look like:</p>
<h1 style="color:black;">The Music Just Turns Me On</h1>
<p>Name:<br />
<input type="text"/><br/><br />
Age:<br />
<input type="text" size="1"/></p>
<input type="submit" value="Add new artist">
<h2 style="color:black;">Available artists</h2>
<p>... HTML output omitted ...</p>
<p>On the artist details page, let's implement the ability to add a new song via a form_tag. We need a list of available genres dynamically generated from the database available to the details.rhtml view. This will go into the ArtistController's details method:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">  <span style="color:#9966CC; font-weight:bold;">def</span> details
    <span style="color:#0066ff; font-weight:bold;">@artist</span> = Artist.<span style="color:#9900CC;">find_by_id</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:id</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@songs</span> = <span style="color:#0066ff; font-weight:bold;">@artist</span>.<span style="color:#9900CC;">songs</span>
    <span style="color:#0066ff; font-weight:bold;">@genres</span> = Genre.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:all</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Open the details.rhtml view and add the following right under the header:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&lt;%</span> form_tag <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:addsong</span>, <span style="color:#ff3333; font-weight:bold;">:id</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@artist</span>.<span style="color:#9900CC;">id</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    Title: <span style="color:#006600; font-weight:bold;">&lt;%</span>= text_field <span style="color:#ff3333; font-weight:bold;">:song</span>, <span style="color:#ff3333; font-weight:bold;">:title</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    Duration (seconds): <span style="color:#006600; font-weight:bold;">&lt;%</span>= text_field <span style="color:#ff3333; font-weight:bold;">:song</span>, <span style="color:#ff3333; font-weight:bold;">:duration</span>, <span style="color:#ff3333; font-weight:bold;">:size</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">3</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    &lt;br /&gt;
    <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#0066ff; font-weight:bold;">@genres</span>.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>cat<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
        <span style="color:#006600; font-weight:bold;">&lt;%</span>= radio_button <span style="color:#ff3333; font-weight:bold;">:song</span>, <span style="color:#ff3333; font-weight:bold;">:genre_id</span>, cat.<span style="color:#9900CC;">id</span> <span style="color:#006600; font-weight:bold;">%&gt;&lt;%</span>= cat.<span style="color:#9900CC;">name</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    <span style="color:#006600; font-weight:bold;">&lt;%</span>= submit_tag <span style="color:#996600;">'Add song'</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span></pre></td></tr></table></div>

<p>This form will have a title and duration textfield, <i>N</i>(in this example, 5) genre radio buttons and a submit button. The radio_button helper accepts an object name (:song), an attribute name (in this case :genre_id, which can be accessed as params[:song].genre_id) and a tag value for that option (in our case, the numerical ID of the genre). We pass :id to the form_tag helper because we need it to lookup the artist record in the :addsong method, which we will now create. Open artists_controller.rb and add the following in the class body:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> addsong
    <span style="color:#008000; font-style:italic;"># Create new song</span>
    <span style="color:#0066ff; font-weight:bold;">@song</span> = Song.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:song</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
    <span style="color:#008000; font-style:italic;"># Find artist and append new song to his current array of songs</span>
    <span style="color:#0066ff; font-weight:bold;">@artist</span> = Artist.<span style="color:#9900CC;">find_by_id</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:id</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@artist</span>.<span style="color:#9900CC;">songs</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> <span style="color:#0066ff; font-weight:bold;">@song</span>
    <span style="color:#0066ff; font-weight:bold;">@song</span>.<span style="color:#5A0A0A; font-weight:bold;">save</span>
&nbsp;
    <span style="color:#5A0A0A; font-weight:bold;">redirect_to</span> <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'details'</span>, <span style="color:#ff3333; font-weight:bold;">:id</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:id</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Save. Run server script. Be amazed -- Unless it doesn't work; In which case compare your code with mine and make sure there are no typos, paying attention to nested brackets and colons.</p>
<h1 style="color:black;">The Music Just Turns Me On</h1>
<p>Title:<br />
<input id="song_title" name="song[title]" size="30" type="text" />
Duration (seconds):<br />
<input id="song_duration" name="song[duration]" size="3" type="text" /></p>
<input id="song_genre_id_1" name="song[genre_id]" type="radio" value="1" />Bluegrass</p>
<input id="song_genre_id_2" name="song[genre_id]" type="radio" value="2" />Goa Trance</p>
<input id="song_genre_id_3" name="song[genre_id]" type="radio" value="3" />Doo Wop</p>
<input id="song_genre_id_4" name="song[genre_id]" type="radio" value="4" />Emo</p>
<input id="song_genre_id_5" name="song[genre_id]" type="radio" value="5" />Blues rock</p>
<input name="commit" type="submit" value="Add song" />
<h2 style="color:black;">Available artists</h2>
<p>... HTML output omitted ...</p>
<h2>Deleting Records: Remember Josh Breckman</h2>
<p>Be cautious if you attempt to implement functionality to delete records. Do not use the link_to helper to destroy/delete records! Requests that change the state of a program should be done using POST, not GET. If the user accidently reloads a page, it shouldn't change anything in the application. Firefox gives you a warning if you try to reload the page when data has been sent via POST.</p>
<p>You can remove records using the Model.destroy method. A safe alternative to link_to is button_to. Read the following links:</p>
<ul>
<li><a href="http://blog.moertel.com/articles/2005/05/08/taking-the-unsafe-gets-out-of-rails">Taking the unsafe GETs out of Rails</a></li>
<li><a href="http://worsethanfailure.com/Articles/The_Spider_of_Doom.aspx">The Spider of Doom</a></li>
</ul>
<h2>Exercises for the 1337 h4x0r</h2>
<ol>
<li>Give your users the ability to add and remove genres.</li>
<li>Break your application by passing it garbage (for example, http://domain.cxm/artists/view/wheeeeeee) and then fix it so it gracefully handles this input by implementing error handling.</li>
<li>Use form_for to add the ability to edit song details.</li>
<li>Use a layout to make 'Browse by artists' and 'Browse by genres' links universal throughout the app.</li>
<li>Create a website, use Gimp to design an award-winning logo, and then market this and use some of the earnings to order me an Ethanol IV drip.</li>
</ol>
<p><i>Thanks to <a href="http://flickr.com/photos/jcanady/384832937/">jcanady</a> for the photo.</i></p>
<div class="externallinks" style="font-size:80%;">
<strong>External links</strong></p>
<ul>
<li><a href="http://www.railsforum.com/viewtopic.php?id=265">Beginning Relationships</a></li>
<li><a href="http://www.railsenvy.com/2007/8/8/activerecord-tutorial">ActiveRecord Tutorial (rails envy)</a></li>
<li><a href="http://wiki.rubyonrails.org/rails/pages/ActiveRecord">ActiveRecord (RoR wiki)</a></li>
</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>http://biodegradablegeek.com/2007/12/understanding-basic-database-relationships-in-rails/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Using Vim as a Complete Ruby on Rails IDE</title>
		<link>http://biodegradablegeek.com/2007/12/using-vim-as-a-complete-ruby-on-rails-ide/</link>
		<comments>http://biodegradablegeek.com/2007/12/using-vim-as-a-complete-ruby-on-rails-ide/#comments</comments>
		<pubDate>Thu, 13 Dec 2007 23:11:46 +0000</pubDate>
		<dc:creator>Isam</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[editors]]></category>
		<category><![CDATA[gvim]]></category>
		<category><![CDATA[ide]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://biodegradablegeek.com/2007/12/13/using-vim-as-a-complete-ruby-on-rails-ide/</guid>
		<description><![CDATA[

NOTE: If you are experiencing segmentation faults with vim and rails.vim, see this post.
When coding in Ruby on Rails, you&#8217;ll usually be switching between files and running scripts a lot. It can be time-consuming and frustrating coding Rails using a traditional text editor designed for working on big files individually. Vim lets you hop around [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/wp-content/uploads/2007/12/vi_traced_with_optical_mouse.jpg" alt="vi traced with an optical mouse" align="left" title="Using Vim as a Complete Ruby on Rails IDE" /></p>
<p><br/><br />
<strong>NOTE:</strong> If you are experiencing segmentation faults with vim and rails.vim, <a href="http://biodegradablegeek.com/2008/08/has-vimrailsvim-been-crashing-lately-heres-why/">see this post</a>.</p>
<p>When coding in Ruby on Rails, you&#8217;ll usually be switching between files and running scripts a lot. It can be time-consuming and frustrating coding Rails using a traditional text editor designed for working on big files individually. Vim lets you hop around within a file with enough speed to activate the cosmic treadmill &#8211; but without a plethora of hacks and custom key mappings, it&#8217;s weak as a Rails IDE. Fortunately, for those of us who are reluctant to kick the vim habit, <a href="http://tpope.net">Tim Pope</a> comes to the rescue with rails.vim; A plugin that makes working with Rails in vim painless and efficient. In this guide, I will explain how to install and use rails.vim, along with a few other plugins you&#8217;ll find useful when writing Rails applications.<br />
<span id="more-42"></span></p>
<p>Vim would certainly fail the <i>mom test</i>, and it&#8217;s not something you can learn in one sitting. Learning vim is a lifelong process, and there are many sites and books that go over it extensively, therefore I won&#8217;t do that here. This guide assumes that you at least know what vim is and can open, edit and save files. Rails.vim works for vim, gvim and <a href="http://cream.sourceforge.net/">Cream</a>, so <i>vim</i> in this article is referring to any of these three, unless otherwise stated.</p>
<p>For those who prefer Emacs, check out <a href="http://steve.yegge.googlepages.com/effective-emacs">Effective Emacs by Steve Yegge</a> and the official Wiki&#8217;s <a href="http://wiki.rubyonrails.org/rails/pages/HowToUseEmacsWithRails">HowTouseEmacsWithRails</a>.</p>
<pre>
<strong>TOC</strong>
<a href="#config">Configuring vim/gvim</a>
<a href="#install">Rails.vim and Other Helpful Plugins</a>
<a href="#usage">Usage and Examples</a>
    <a href="#newp">Starting a New Project and Setting Up The Database</a>
        <a href="#dbsetup">Database.yml Setup</a>
    <a href="#models">Generating Models</a>
    <a href="#migrations">Migrations and :Rake</a>
        <a href="#pattern">:Rmigration <i>pattern</i></a>
        <a href="#related">Related Files and The Command :R and its Mapping ]f</a>
    <a href="#dbext">A Glimpse of the Vim Database Extension Plugin</a>
    <a href="#navigation">Controllers, Views and Interfile Navigation</a>
        <a href="#r">:R or ]f</a>
        <a href="#rview">:Rview <i>[[controller/]view]</i></a>
        <a href="#rfind">:Rfind <i>[name]</i></a>
        <a href="#gf">gf ("goto file")</a>
    <a href="#views">Views and Partials</a>
    <a href="#surround">We've Got You Surrounded</a>
        <a href="#caveats">Caveats</a>
        <a href="#add">Adding Surroundings</a>
        <a href="#rep">Replacing Surroundings</a>
        <a href="#rm">Removing Surroundings</a>
        <a href="#custom">Rails.vim and Custom Surroundings</a>
<a href="#neverends">But Wait, There's More</a>
</pre>
<h2 id="config">Configuring Vim/gvim</h2>
<p>Open your vim configuration file or create one if it doesn&#8217;t exist (i.e., new installation):</p>
<ul>
<li>$HOME/.vimrc in Linux and Mac OS X (might be ~/.gvimrc instead)</li>
<li>$HOME\_vimrc (or $HOME\_gvimrc) in Windows</li>
</ul>
<p>If you&#8217;re having trouble finding out where the config file goes, type &#8220;:version&#8221; and hit enter in vim for a list of compile flags, options and directories vim is using.</p>
<p>Add the following to the file and save it (if you must worry about what they do, see <a href="http://vimdoc.sourceforge.net/htmldoc/">the vimdoc</a>)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">filetype on  &quot; Automatically detect file types.
set nocompatible  &quot; We don't want vi compatibility.
&nbsp;
&quot; Add recently accessed projects menu (project plugin)
set viminfo^=!
&nbsp;
&quot; Minibuffer Explorer Settings
let g:miniBufExplMapWindowNavVim = 1
let g:miniBufExplMapWindowNavArrows = 1
let g:miniBufExplMapCTabSwitchBufs = 1
let g:miniBufExplModSelTarget = 1
&nbsp;
&quot; alt+n or alt+p to navigate between entries in QuickFix
map &lt;silent&gt; &lt;m-p&gt; :cp &lt;cr&gt;
map &lt;silent&gt; &lt;m-n&gt; :cn &lt;cr&gt;
&nbsp;
&quot; Change which file opens after executing :Rails command
let g:rails_default_file='config/database.yml'
&nbsp;
syntax enable</pre></td></tr></table></div>

<p>Before installing rails.vim, you may want to glance over some additional (g)vim options I use. Otherwise, skip this optional step and <a href="#install">jump directly</a> to the installation.</p>
<p>The following settings in my config are worth looking over. These can be appended to the same vimrc file as above:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">set cf  &quot; Enable error files &amp; error jumping.
set clipboard+=unnamed  &quot; Yanks go on clipboard instead.
set history=256  &quot; Number of things to remember in history.
set autowrite  &quot; Writes on make/shell commands
set ruler  &quot; Ruler on
set nu  &quot; Line numbers on
set nowrap  &quot; Line wrapping off
set timeoutlen=250  &quot; Time to wait after ESC (default causes an annoying delay)
&quot; colorscheme vividchalk  &quot; Uncomment this to set a default theme
&nbsp;
&quot; Formatting (some of these are for coding in C and C++)
set ts=2  &quot; Tabs are 2 spaces
set bs=2  &quot; Backspace over everything in insert mode
set shiftwidth=2  &quot; Tabs under smart indent
set nocp incsearch
set cinoptions=:0,p0,t0
set cinwords=if,else,while,do,for,switch,case
set formatoptions=tcqr
set cindent
set autoindent
set smarttab
set expandtab
&nbsp;
&quot; Visual
set showmatch  &quot; Show matching brackets.
set mat=5  &quot; Bracket blinking.
set list
&quot; Show $ at end of line and trailing space as ~
set lcs=tab:\ \ ,eol:$,trail:~,extends:&gt;,precedes:&lt;
set novisualbell  &quot; No blinking .
set noerrorbells  &quot; No noise.
set laststatus=2  &quot; Always show status line.
&nbsp;
&quot; gvim specific
set mousehide  &quot; Hide mouse after chars typed
set mouse=a  &quot; Mouse in all modes</pre></td></tr></table></div>

<p>The following optional commands are helpful but require explicit creation of directories and files:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">&quot; Backups &amp; Files
set backup                     &quot; Enable creation of backup file.
set backupdir=~/.vim/backups &quot; Where backups will go.
set directory=~/.vim/tmp     &quot; Where temporary files will go.</pre></td></tr></table></div>

<p>Run vim to make sure it doesn&#8217;t halt to display any warnings or error messages. If it does, check that the specific folders (~/.vim/skeletons and ~/.vim/backups etc) exist and vim has write permission on them.</p>
<h2 id="install">Rails.vim and Other Helpful Plugins</h2>
<p>Installing vim plugins just requires putting files where they belong in vim&#8217;s root directory. We will be installing rails.vim along with some dependency plugins and a few others that make coding Rails in vim much simpler.</p>
<p>Below is a list of all the plugins you need to download and install. If they are <strong>.vim files</strong>, move them into your <i>plugin</i> folder, probably $HOME/.vim/plugin or $VIM\vimfiles\plugin (probably C:\vim\vimfiles\plugin). <strong>Doc files (.txt)</strong> go in $HOME/.vim/doc or vimfiles\doc\. Do the same with the contents of compressed files after you&#8217;ve extracted them. Again, if you&#8217;re having trouble locating where these files should go, type &#8220;:version&#8221; in vim and hit enter.</p>
<ul>
<li><a href="http://www.vim.org/scripts/script.php?script_id=1567">rails.vim</a>: This is the magic. The rails.zip file contains plugin/rails.vim and doc/rails.txt. Both should be moved into their proper location in your root vim directory ($VIM).</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=69">Project</a>: This adds a list of frequently used files to the lefthand side of vim. Rails.vim utilizes this script to create a directory tree of your Rails application. You&#8217;re probably familiar with this feature already, as is a basic feature of most modern IDEs.</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=197">genutils 1.20 <strong>(NOT 2.x)</strong></a>: Adds many useful functions</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=171">multvals.vim</a>: genutils depends on this.</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=159">minibufexpl.vim</a>: This adds (ugly, but functional) tabs to vim, making it much easier to keep track of the many files you&#8217;ll be working on simultaneously.</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=356">dbext.vim</a>: Adds database support to vim. This integrates seemlessly with rails.vim. More on it below.</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=1697">surround</a>: Surround.vim adds mappings to let you easily work with &#8220;surroundings&#8221; in pairs. Such as { }, &#8221; &#8221; and < >. More on it below.</li>
</ul>
<p>To get the help files working, Rails needs to generate help tags from the txt files you placed in the doc directory. Open vim and in <i>normal</i> (command) mode type the following and hit enter:<br />
<strong>Linux:</strong> :helptags $HOME/.vim/doc<br />
<strong>Windows:</strong> :helptags $VIM\vimfiles\doc</p>
<p>Your directory might differ from the above. In which case, again, check &#8220;:version<enter>&#8221;</p>
<p>Make sure it worked:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:help rails</pre></td></tr></table></div>

<p>For more information on vim&#8217;s help feature, use <strong>:help help</strong> or read about it <a href="http://www.vim.org/htmldoc/various.html#:help">in your browser</a>. For help about a specific command, use :help <i>command</i>. Command can be a vim, rails.vim or other plugin command. For example <i>:help rails</i> or <i>:help rgenerate</i>.</p>
<h2 id="usage">Usage and Examples</h2>
<p>Usage might seem intimidating at first because the plugins have-on top of vim&#8217;s already rich set of functions-added so much more functionality and commands to memorize, but you&#8217;ll quickly realize that getting used to rails.vim is easy due to the natural command names (and tab completion). Let&#8217;s begin by creating a dummy rails project.</p>
<h3 id="newp">Starting a New Project and Setting Up The Database</h3>
<p>In Cream or gvim, you can create projects using the menu </strong>Plugin -> Rails -> Projects -> New</strong>. Alternatively, you can use the <strong>:Rails</strong> command in <i>normal</i> mode. Both the menu option and the :Rails command are wrappers for the native <i>rails</i> application, making it possible to pass them what you would normally pass <i>rails</i> in the console.</p>
<p><i>If you do not specify an absolute path when passing :Rails your project name, the rails application will be generated in the current working directory, usually the directory you were in when you started vim.</i></p>
<p>Let&#8217;s create a new framework named <i>dummy</i>. This command is typed in vim while in command mode (not the mode you type content in) and followed with the Enter key. Change /tmp/ to where ever you want this to reside (I.e., C:\Windows\Temp\):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rails /tmp/dummy</pre></td></tr></table></div>

<p><strong id="dbsetup">Database.yml Setup</strong><br />
The usual rails output will scroll across the screen and you will be dumped at the default file you specified in the vimrc file (g:rails_default_file). This will be README by default. If you haven&#8217;t changed it to database.yml like in my config above, you can jump to the database config file by typing <strong>:Rfind database.yml</strong>.</p>
<p>Put your database information under <i>dummy_development</i> and save as usual (:w). Now creating our dummy_development database is as easy as one short command:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rdbext!</pre></td></tr></table></div>

<p><i>(You can use a database frontend (like the excellent <a href="http://www.phpmyadmin.net">PHPMyAdmin</a>) or the mysql command in a console to create your dummy_development database if you did not install dbext.)</i></p>
<p><strong>Note:</strong> This issues a CREATE DATABASE command on the Rails environment in $RAILS_ENV, which is <i>development</i> by default, but you can have it create the <i>test</i> and <i>production</i> environments as well:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rdbext! test
:Rdbext! production</pre></td></tr></table></div>

<p>The last loaded environment configuration is what will be used throughout the Rails application. To change the environment, just provide the desired one as a parameter to the :Rdbext command (notice lack of bang: <strong>!</strong>). If you&#8217;ve created three environments and want to switch to the test environment:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rdbext test</pre></td></tr></table></div>

<p>This commands opens up a Results tab and displays the results on the bottom of the screen in a new window. Sometimes, this window can be intrusive and downright annoying. To close it, click it and hit <strong>ctrl+w</strong>, let go of both and quickly hit <strong>c</strong>.</p>
<p>For more information, check <strong>:help Rdbext</strong>. More on DBExt later.</p>
<h3 id="models">Generating Models</h3>
<p>If you wish to run something in the application&#8217;s script directory, you can use :Rscript:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rscript about
:Rscript console
:Rscript breakpointer
etc...</pre></td></tr></table></div>

<p>but you will probably never need to, as Rails.vim provides wrappers for most of Rails&#8217; scripts and functions. The names of these will usually be <strong>:R</strong> followed by the name of the script. For example, :Rgenerate, :Rserver, :Rconsole, etcetra&#8230;</p>
<p>:Rgenerate takes the same parameters as Rails&#8217; generate script. Let&#8217;s generate a model named Thing:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rgenerate model Thing</pre></td></tr></table></div>

<p>The model file is automatically loaded and given focus after its creation. Notice that you can still access database.yml via its tab on top of the vim window. Double click a tab to open it, and click it once to give it focus, then hit <strong>d</strong> to close it. Try that now on database.yml (and Results if it&#8217;s still open). More on tabs and the minibufexpl later.</p>
<h3 id="migrations">Migrations and :Rake</h3>
<p>Let&#8217;s edit the model&#8217;s migration file, which is created automatically for each generated model. You have a number of choices for jumping to this file:</p>
<p><strong id="pattern">:Rmigration <i>pattern</i></strong><br />
The optional <i>pattern</i> can be any part of the migration&#8217;s filename (in this case, 001_create_things.rb). You can use <i>things</i> (notice it&#8217;s plural) because it matches the filename:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rmigration things</pre></td></tr></table></div>

<p>The migration number with or without the zeros. All three examples open the same migration:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rmigration 1
:Rmigration 01
:Rmigration 001</pre></td></tr></table></div>

<p>or any string of characters that match part of that migration&#8217;s filename without causing an ambiguity, like 001_crea<strong>te_t</strong>hings.rb:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rmigration te_t</pre></td></tr></table></div>

<p>Rmigration is context aware. It will default to opening the <i>related</i> migration file if executed without a parameter while the model file is open:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rmigration</pre></td></tr></table></div>

<p>More on related files below.</p>
<p><strong>Related files and the command :R and its mapping ]f</strong><br />
The <strong>:R</strong> command or its mapping <strong>]f</strong> open up the related file of whatever is currently open. A related file is something that is usually associated with the file you are opening. This is a construct in rails.vim, and that&#8217;s where the rules are defined. For example, a model&#8217;s related file is its migration. Even though both can be independent (you can have migrations without models and vice versa). Don&#8217;t think about this too much.</p>
<p>Below is an excerpt from <strong>:help rails-related</strong>. It shows a list of what file will be open when :R is issued while the Current File is open:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">&lt;strong&gt;Current File            Related File&lt;/strong&gt;
model            related migration
controller (in method)    template (view)
template (view)            controller (jump to method)
migration            next migration
config/routes.rb        config/environment.rb</pre></td></tr></table></div>

<p>Open the migration file and add the following to the create_table block in the self.up method:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:description</span>, <span style="color:#ff3333; font-weight:bold;">:text</span>
t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:weight</span>, <span style="color:#ff3333; font-weight:bold;">:integer</span></pre></td></tr></table></div>

<p>After writing your self.up, you can use :Rinvert to have self.down automatically generated. You don&#8217;t have to do this here because self.down is already filled in (drop_table), but let&#8217;s try it anyway by creating a test table called &#8220;test&#8221; and using :Rinvert to update self.down. Your self.up should now look like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">up</span>
    create_table <span style="color:#ff3333; font-weight:bold;">:things</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>t<span style="color:#006600; font-weight:bold;">|</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:description</span>, <span style="color:#ff3333; font-weight:bold;">:text</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:weight</span>, <span style="color:#ff3333; font-weight:bold;">:integer</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    create_table <span style="color:#ff3333; font-weight:bold;">:test</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>t<span style="color:#006600; font-weight:bold;">|</span>
      t.<span style="color:#9900CC;">column</span> <span style="color:#ff3333; font-weight:bold;">:hi</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>and after running :Rinvert, your self.down will be:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;">  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">down</span>
    drop_table <span style="color:#ff3333; font-weight:bold;">:test</span>
    drop_table <span style="color:#ff3333; font-weight:bold;">:things</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>:Rinvert works great for most commands, even some complex queries, but it can&#8217;t reverse everything. A low level SQL query or a blank self.up might produce an IrreversableMigration error. Let&#8217;s apply our migration to the database by running <strong>:Rake</strong>. It defaults to db:migrate when run in the context of our migration file.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rake</pre></td></tr></table></div>

<h3 id="dbext">A Glimpse of the Vim Database Extension Plugin</h3>
<p>DBExt is powerful and deserves its own paper, but before getting derailed from our main topic, here are some useful DBExt commands:</p>
<p><strong>:DBDescribeTable <i>table</i></strong> outputs a table&#8217;s columns and their data types. Run it now on the <i>things</i> table:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:DBDescribeTable things
&nbsp;
Connection: T(MYSQL)  D(bic_development)  U(username)
Field    Type    Null    Key        Default        Extra
id    int(11)    NO        PRI        NULL        auto_increment
description    text    YES        NULL
weight    int(11)    YES        NULL</pre></td></tr></table></div>

<p><strong>:DBExecSQL <i>query</i></strong> executes low level SQL queries that are either under the cursor, or passed as parameters. Let&#8217;s use it to populate our table:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:DBExecSQL INSERT INTO things VALUES (1, 'Worlds fattest man', 1200);
:DBExecSQL INSERT INTO things VALUES (2, 'Four quarter pounders', 1);</pre></td></tr></table></div>

<p>Let&#8217;s view the contents of the <i>things</i> table:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:DBSelectFromTable things</pre></td></tr></table></div>

<p><i>If the results window on the bottom gets stuck, click it and then hit ctrl+w the c to close it.</i></p>
<p>Read the extensive help file using <strong>:help DBExt</strong>.</p>
<h3 id="navigation">Controllers, Views and Interfile Navigation</h3>
<p>Let&#8217;s create a controller and a skeleton for a method named index:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rgenerate controller Things index</pre></td></tr></table></div>

<p>We want to display all the records from our Thing table in our index view. Let&#8217;s add some code this controller&#8217;s index method:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> index
    <span style="color:#0066ff; font-weight:bold;">@people</span> = Thing.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:all</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>For test purposes later, add the following method to ThingsController, under the index method:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> viewless
    <span style="color:#0066ff; font-weight:bold;">@cast</span> = <span style="color:#996600;">&quot;Cloud Strife&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Since we passed a method name (<i>index</i>) to :Rgenerate, Rails has automatically generated a view for that method. We have a number of ways to navigate to that view:</p>
<p><strong id="r">:R or ]f</strong><br />
The Related command was discussed above under <a href="#migrake">Migrations and :Rake</a>. A controller can have many views, so :R looks at the current method the cursor resides in to look up what view to open. Place the cursor anywhere in the index method and type :R (or hit <i>]f</i>) to open up index.rhtml.</p>
<p>This command only works if the related file exists. If the view doesn&#8217;t exist, you&#8217;ll get an &#8220;E345: Can&#8217;t find file &#8230; in path&#8221; error. Try this by putting the cursor on the viewless method before running the :R command again.</p>
<p>You can use :RS to split (what the S stands for) the current window into two, allowing you to view and edit both the controller and view simultaneously.</p>
<p><strong id="rview">:Rview <i>[[controller/]view]</i></strong><br />
Typed with no arguments, this command behaves the same as :R. If that view doesn&#8217;t exist, you can specify a name, either by the full path or just the view name and extension, and that view will be created.</p>
<p>For example, let&#8217;s create a view on the fly for the viewless method (extension is mandatory):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rview viewless.rhtml</pre></td></tr></table></div>

<p>We haven&#8217;t defined a controller above, so by default, :Rview assumes it is for the current controller. It will go into app/views/things/. We could specify a controller by using <strong>:Rview controller/view_name.extension</strong>.</p>
<p>Note that the file is only generated in memory and must be saved to disk explicitly (:w).</p>
<p><strong>Alternating between files</strong></p>
<p>A lot of times, you&#8217;ll be working exclusively on two files, back and forth. To alternate between the current file and the last file you were editing, use <i>CTRL+^</i> (although in practice, you&#8217;re actually just hitting CTRL+6).</p>
<p>Rails.vim also has an <i>alternate</i> command (:A or the [f mapping), similar in function to related. It usually takes you to the current file's test file.</p>
<p>From <strong>:help rails-alternate</strong>, this tells you what the alternate file will be for the Current File open:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">&lt;strong&gt;Current file      Alternate file&lt;/strong&gt;
model                               unit test
controller (in method)    functional test
template (view)              helper
migration                         previous migration
config/routes.rb               config/database.yml</pre></td></tr></table></div>

<p><strong id="rfind">:Rfind <i>[name]</i></strong><br />
Like vim&#8217;s :find command, this one also opens a file it finds either by the name you pass it or by whatever is under the cursor (behaves similarly to <i>gf</i>, more on that below). Rails.vim enhances the native command by giving it the ability to find files by controller and model name.</p>
<p>This opens the Thing model:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rfind thing</pre></td></tr></table></div>

<p>This opens the Things controller (case sensitive):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rfind ThingsController</pre></td></tr></table></div>

<p>This opens the index.rhtml view (you must be in the ThingsController):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:Rfind index</pre></td></tr></table></div>

<p><strong id="gf">gf (&#8220;goto file&#8221;)</strong><br />
In rails.vim, the <i>gf</i> mapping is used to jump to a file under the cursor taking context into account. The following is from <strong>:help rails-gf</strong>:<br />
&#8212;<br />
Example uses of gf, and where they might lead. <i>(* indicates cursor position)</i><br />
    Pos*t.find(:first)<br />
    app/models/post.rb</p>
<p>    has_many :c*omments<br />
    app/models/comment.rb</p>
<p>    link_to &#8220;Home&#8221;, :controller => :bl*og<br />
    app/controllers/blog_controller.rb</p>
<p>    <%= render :partial => &#8217;sh*ared/sidebar&#8217; %><br />
    app/views/shared/_sidebar.rhtml</p>
<p>    <%= stylesheet_link_tag :scaf*fold %><br />
    public/stylesheets/scaffold.css</p>
<p>    class BlogController < Applica*tionController<br />
    app/controllers/application.rb</p>
<p>    class ApplicationController < ActionCont*roller::Base<br />
    .../action_controller/base.rb</p>
<p>    fixtures :pos*ts<br />
    test/fixtures/posts.yml</p>
<p>    layout :pri*nt<br />
    app/views/layouts/print.rhtml</p>
<p>    # In the Blog controller<br />
    def li*st<br />
    app/views/blog/list.rhtml</p>
<p>    <%= link_to "New", new_comme*nt_path %><br />
    app/controllers/comments_controller.rb (jumps to def new)</p>
<p>In the last example, the controller and action for the named route are determined by evaluating routes.rb as Ruby and doing some introspection. This means code from the application is executed. Keep this in mind when navigating unfamiliar applications.<br />
&#8212;</p>
<p>Add the following to the index.rhtml view file, overwriting the default code already in there:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;h1&gt;All the things in our Thing table&lt;/h1&gt;
&amp;lt;h1&amp;gt;All the things in our Thing table&amp;lt;/h1&amp;gt;
&lt;ol&gt;
  &lt;% @stuff.each do |x| %&gt;
    &lt;li&gt;
    &lt;%= x.description %&gt; (weight: &lt;%= x.weight %&gt; pound(s))
    &lt;/li&gt;
  &lt;% end %&gt;
&lt;/ol&gt;</pre></td></tr></table></div>

<h3 id="views">Views and Partials</h3>
<p>The :Rextract command (:Rpartial is deprecated) makes creating <a href="http://wiki.rubyonrails.org/rails/pages/Partials">partials</a> a breeze. You choose a range of lines and supply the command a name you want for the new partial. The lines get replaced by a call to render the newly created partial, which now holds the lines that were extracted.</p>
<p>Let&#8217;s try using this by delegating output code between the &lt;li&gt; and &lt;/li&gt; tags in our index.rhtml view into a partial named &#8220;ppp&#8221; by explicitly defining the line numbers (your line numbers might not match. Alter it accordingly):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">:5,5Rextract ppp</pre></td></tr></table></div>

<p>A new partial with the filename _ppp.rhtml is created containing line #5 from our index.rhtml view. Line #5 now is a call to render the newly created ppp view: <i><%= render :partial => &#8216;ppp&#8217; %></i> &#8211; The new partial only exists in memory at this point, and must be saved to disk explicitly.</p>
<p>This could also have been done in visual mode, selecting the lines we want extracted visually instead of by line numbers. Place the cursor at the beginning of the line, press v to enter visual mode and hit &#8216;$&#8217; (shift+4) to jump to the end of the line, selecting the entire line along the way. Now hit : and type :Rextract ppp (it will come out as <i>:&#8217;<,'>Rextract ppp</i>) and hit enter. Same effect as above.</p>
<h3 id="surround">We&#8217;ve Got You Surrounded</h3>
<p>Whether you&#8217;re coding, writing, or editing, Tim Pope&#8217;s surround plugin is very useful. It adds vim mappings to add, remove or edit &#8220;surroundings.&#8221; A surrounding is a pair of parentheses, brackets, quotes, tags, etc.</p>
<p>Some mappings require that you press the first few keystrokes within a second. For full functionality, make sure you&#8217;re using vim 7 or greater. Let&#8217;s begin by making sure the plugin is installed and works properly by testing a command:</p>
<p>Type <i>(hello world)</i> into vim, and with your cursor anywhere in that phrase, hit <strong>ds(</strong>. If <i>(hello world)</i> turns to <i>hello world</i>, the plugin is working fine. If not, then make sure you&#8217;re installed it correctly and are using Vim 7.0.</p>
<p><strong id="caveats">Caveats</strong><br />
* The keystrokes need to be typed in succession very fast. The <i>timeoutlen</i> setting in the vim config file can impair the ys* functions. The smaller the value for <i>timeoutlen</i>, the less time you have in between keystrokes to ensure vim catches the command. I set <i>timeoutlen</i> to 200, but put 250 as the value in the example vimrc at the beginning of this tutorial. Delete this setting or use a higher value (300+) if you&#8217;re having trouble using commands like yssa or yss.</p>
<p>* b, B, r, and a are aliases for ), }, ], and > respectively, and t represents a pair of HTML or XML tags.</p>
<p>* In the examples below, the cursor position is represented by an asterisk (*).</p>
<p><strong id="add">Adding Surroundings</strong><br />
You can add a pair of surroundings around a word, line, sentence, paragraph or a specific number of characters.</p>
<p>Adding quotes around a word:<br />
<u>Old text | Command | Result</u><br />
H*eya world | ysiw&#8221; | &#8220;Heya&#8221; world</p>
<p>Adding a pair of tags around a word:<br />
<u>Old text | Command | Result</u><br />
I*talic text | ysiw&lt;i&gt; | &lt;i&gt;Italic&lt;/i&gt; text</p>
<p>Adding arrows around a sentence:<br />
<u>Old text | Command | Result</u><br />
Clandestin*e operation | yssa | &lt;Clandestine operation&gt;</p>
<p>An angry Kenny face:<br />
<u>Old text | Command | Result</u><br />
*>< | yss)yss)yss( | ( ((><)) )<br />
<i>(notice usage of parantheses in the command. Using the opening bracket adds spaces between the target being surrounded.)</i></p>
<p><strong id="rep">Replacing Surroundings</strong><br />
Replacing parentheses with quotes in a word:<br />
<u>Old text | Command | Result</u><br />
(qu*ack) quack | cs(&#8221; | &#8220;quack&#8221; quack</p>
<p>Changing those double quotes to a pair of tags:<br />
<u>Old text | Command | Result</u><br />
&#8220;q*uack&#8221; quack | cs&#8221;<qqqqq> | <qqqqq>quack</qqqqq> quack</p>
<p>Changing those tags to brackets:<br />
<u>Old text | Command | Result</u><br />
&lt;qqqqq&gt;q*uack&lt;/qqqqq&gt; quack | cstr | [quack] quack</p>
<p><strong id="rm">Removing Surroundings</strong><br />
Remove quotes around a word:<br />
<u>Old text | Command | Result</u><br />
Hash &#8220;eater*&#8221;  | ds&#8221; | Hash eater</p>
<p>Remove tags around a word:<br />
<u>Old text | Command | Result</u><br />
&lt;h1&gt;h*ead&lt;/h1&gt; | dst | head</p>
<p>Removing multiple surroundings around a sentence:<br />
<u>Old text | Command | Result</u><br />
{&#8220;(iiight)&#8221;} | ds(ds&#8221;dsB | iiight</p>
<p><strong id="custom">Rails.vim and Custom Surroundings</strong><br />
Rails.vim makes use of the surround plugin by adding a few useful surroundings. These only work when rails.vim is enabled (when RoR projects are open):</p>
<p><u>Old text | Command | Result</u><br />
*end | yss= | <%= end %></p>
<p><u>Old text | Command | Result</u><br />
*end | yss- | <%= end -%></p>
<p><u>Old text | Command | Result</u><br />
*cat | yss# | <%# cat %></p>
<p>You can create custom surroundings. Here&#8217;s one example:<br />
:let g:surround_65 = &#8220;&lt;a href=\&#8221;\&#8221;&gt; \r &lt;/a&gt;&#8221;</p>
<p>65 is the ASCII decimal for the &#8216;A&#8217; character. You can use <a href="http://web.cs.mun.ca/~michael/c/ascii-table.html">an ascii table</a> to find the decimal corresponding to the character you want to use.</p>
<p>Usage:<br />
<u>Old text | Command | Result</u><br />
I*Shot The Sheriff | yssA | &lt;a href=&#8221;"&gt; I Shot The Sheriff &lt;/a&gt;</p>
<p>Be sure to read the extensive help files :help surround and :help rails-surround. They provide details and examples.</p>
<h2 id="neverends">But Wait, There&#8217;s More</h2>
<p>We&#8217;ve merely scratched the surface of rails.vim here. Be sure to check out the <a href="http://rails.vim.tpope.net/">Official rails.vim Website</a>, the <a href="http://tpope.net">author&#8217;s site</a>, and the external links I provided below. For those looking for a more user-friendly, &#8220;real&#8221; GUI-based (as opposed to a TUI) IDE based around vim, try out <a href="http://vimmate.rubyforge.org/">VimMate</a>.</p>
<div class="externallinks" style="font-size:80%;">
<strong>External links</strong></p>
<ul>
<li><a href="http://wiki.rubyonrails.org/rails/pages/HowtoUseVimWithRails">How To Use Vim With Rails (official RoR wiki)</a></li>
<li><a href="http://ruby.about.com/od/railsvim/railsvim_Ruby_on_Rails_IDE.htm">Rails.vim RoR IDE (About.com)</a></li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=1658">NERD tree &#8211; A great plugin that adds a nested file explorer to vim, much like the Project plugin</a></li>
<li><a href="http://eigenclass.org/hiki.rb?rcodetools">rcodetools</a></li>
</ul>
<p><i>Thanks to <a href="http://flickr.com/photos/heyvikram/152929481/">_vikram</a> for the vi photo. It was done using an optical mouse and a long exposure. He was actually attempting to spell out &#8220;vik&#8221;</i>
</div>
]]></content:encoded>
			<wfw:commentRss>http://biodegradablegeek.com/2007/12/using-vim-as-a-complete-ruby-on-rails-ide/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
	</channel>
</rss>

