<?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>stevengharms.com &#187; Rails</title>
	<atom:link href="http://stevengharms.com/category/rails/feed" rel="self" type="application/rss+xml" />
	<link>http://stevengharms.com</link>
	<description>My Blog</description>
	<lastBuildDate>Sat, 21 Apr 2012 19:06:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>PostgreSQL database automatic launch on OSX 10.6 Snow Leopard</title>
		<link>http://stevengharms.com/postgresql-database-automatic-launch-on-osx-10-6-snow-leopard</link>
		<comments>http://stevengharms.com/postgresql-database-automatic-launch-on-osx-10-6-snow-leopard#comments</comments>
		<pubDate>Fri, 05 Feb 2010 04:58:47 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[apple]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://stevengharms.com/?p=1934</guid>
		<description><![CDATA[It took a while to find this, but here&#8217;s my solution Add this file: /Library/LaunchDaemons/org.postgres.launchd.plist &#60;?xml version="1.0" encoding="UTF-8"?&#62; &#60;!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd";&#62; &#60;plist version="1.0"&#62; &#60;dict&#62; &#60;key&#62;Label&#60;/key&#62; &#60;string&#62;org.postgres.launchd&#60;/string&#62; &#60;key&#62;Disabled&#60;/key&#62; &#60;false/&#62; &#60;key&#62;UserName&#60;/key&#62; &#60;string&#62;_pgsql&#60;/string&#62; &#60;key&#62;GroupName&#60;/key&#62; &#60;string&#62;_pgsql&#60;/string&#62; &#60;key&#62;Program&#60;/key&#62; &#60;string&#62;/usr/local/pgsql/bin/postmaster&#60;/string&#62; &#60;key&#62;EnvironmentVariables&#60;/key&#62; &#60;dict&#62; &#60;key&#62;PGDATA&#60;/key&#62; &#60;string&#62;/usr/local/pgsql/data/&#60;/string&#62; &#60;/dict&#62; &#60;key&#62;RunAtLoad&#60;/key&#62; &#60;true/&#62; &#60;/dict&#62; &#60;/plist&#62; You can then load it and unload [...]]]></description>
			<content:encoded><![CDATA[<p>It took a while to find this, but here&#8217;s my solution</p>

<p>Add this file:  /Library/LaunchDaemons/org.postgres.launchd.plist</p>

<pre>
<code >&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd";&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
    <!-- Following the launchd man page enumeration of keys -->
    &lt;key&gt;Label&lt;/key&gt;
      &lt;string&gt;org.postgres.launchd&lt;/string&gt;
    &lt;key&gt;Disabled&lt;/key&gt;
      &lt;false/&gt;
    &lt;key&gt;UserName&lt;/key&gt;
      &lt;string&gt;_pgsql&lt;/string&gt;
    &lt;key&gt;GroupName&lt;/key&gt;
      &lt;string&gt;_pgsql&lt;/string&gt;
    &lt;key&gt;Program&lt;/key&gt;
      &lt;string&gt;/usr/local/pgsql/bin/postmaster&lt;/string&gt;
      &lt;key&gt;EnvironmentVariables&lt;/key&gt;
      &lt;dict&gt;
              &lt;key&gt;PGDATA&lt;/key&gt;
              &lt;string&gt;/usr/local/pgsql/data/&lt;/string&gt;
      &lt;/dict&gt;
    &lt;key&gt;RunAtLoad&lt;/key&gt;
      &lt;true/&gt;
&lt;/dict&gt;
&lt;/plist&gt;</code>
</pre>

<p>You can then load it and unload it by issuing:</p>

<pre>
$ sudo launchctl load /Library/LaunchDaemons/org.postgres.launchd.plist
$ sudo launchctl unload /Library/LaunchDaemons/org.postgres.launchd.plist
</pre>

<p>Now get to making some great Rails stuff!</p>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/postgresql-database-automatic-launch-on-osx-10-6-snow-leopard/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A simple PostGres Question I had:  How to i find out the columns of a table</title>
		<link>http://stevengharms.com/a-simple-postgres-question-i-had-how-to-i-find-out-the-columns-of-a-table</link>
		<comments>http://stevengharms.com/a-simple-postgres-question-i-had-how-to-i-find-out-the-columns-of-a-table#comments</comments>
		<pubDate>Mon, 14 Jan 2008 09:04:15 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1090</guid>
		<description><![CDATA[Google search was un-obvious psql databasename \d table_name]]></description>
			<content:encoded><![CDATA[<p>Google search was un-obvious</p>

<pre>
psql databasename
\d table_name
</pre>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/a-simple-postgres-question-i-had-how-to-i-find-out-the-columns-of-a-table/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Rails] Associations</title>
		<link>http://stevengharms.com/rails-associations</link>
		<comments>http://stevengharms.com/rails-associations#comments</comments>
		<pubDate>Mon, 14 Jan 2008 08:54:09 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1089</guid>
		<description><![CDATA[Yesterday I found out I had made a major boo-boo in setting up an ActiveRecord::Association. Imagine a &#8220;Widget&#8221; model that is composited of serveral other fields. You might think to yourself. &#8220;An Widget has a SKU ( housed in table &#8216;skus&#8217; based on model SKU ), a widget has a color, etc.&#8221; You then might [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I found out I had made a major boo-boo in setting up an <a href="http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html" title="Module: ActiveRecord::Associations::ClassMethods">ActiveRecord::Association</a>.</p>

<p>Imagine a &#8220;Widget&#8221; model that is composited of serveral other fields.  You might think to yourself.</p>

<p>&#8220;An Widget has a SKU ( housed in table &#8216;skus&#8217; based on model SKU ), a widget has a color, etc.&#8221;</p>

<p>You then might model your code such that</p>

<pre>
    Widget < ActiveRecord::Base
      has_one :sku
      has_one :color
    end
</pre>

<p>And accordingly</p>

<pre>
    SKU < ActiveRecord::Base
      belongs_to :widget
    end
</pre>

<p>This is <strong>wrong</strong>.</p>

<p>You must think in terms of the most &#8220;atomic&#8221; element.  What&#8217;s the relationship of a SKU?  A SKU &#8220;has one&#8221; product to which it is applicable.  You see, what you&#8217;ve done above is <strong>absolutely reverse</strong> of the way it should be.</p>

<p>Think this way:</p>

<pre>
    SKU < ActiveRecord::Base
      has_one :widget
    end
</pre>

<p>And then just add the mirror entry, for completeness</p>

<pre>
    Widget < ActiveRecord::Base
      belongs_to :sku
    end
</pre>

<p>You can see <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html">this explained in the Rails API</a>:</p>

<pre>
class Employee < ActiveRecord::Base
    has_one <img src='http://stevengharms.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ffice
end

class Office < ActiveRecord::Base
   belongs_to :employee    # foreign key - employee_id
end
</pre>

<p>If you find yourself using the primary key of the composite entity to find something in the the constituent table or getting into weird sorts of problems with .create() or find yourself thinking that you may need to implement something like (although it is pretty cool):</p>

<pre>
    $ irb
    irb(main):001:0> class K
    irb(main):002:1> end
    => nil
    irb(main):003:0> k1 = K.new
    => #<K:0xb7fc1788>
    irb(main):004:0> k2 = eval('K').new
    => #<K:0xb7fb8094>
    irb(main):005:0> k3 = Object.const_get('K').new
    => #<K:0xb7fb1474>
</pre>

<p>[<a href="http://readlist.com/lists/ruby-lang.org/ruby-talk/1/6405.html">Reference</a>]</p>

<p>The real difficulty here is with how English speakers construe the transitivity of the phrase &#8220;has one&#8221;.  Does this mean:</p>

<ul>
<li>X is a superior containing entity i.e. &#8220;contains&#8221; (&#8220;The happy meal has one hamburger and one toy&#8221;)  </li>
<li>X is uniquely assigned in a relationship (&#8220;The parolee has one parole officer&#8221;)  </li>
</ul>

<p>The word &#8220;relationship&#8221; in the second bullet is the use of &#8220;has_one&#8221; that Rails uses the phrase &#8220;has_one&#8221; to signify.</p>

<p>If, when getting your object model to work in Rails seems really hard and sorta backwards, you should say &#8220;this seems needlessly hard, maybe I&#8217;m doing it the wrong way&#8221; and <em>bail out</em> of that design.  The <a href="http://lolcatz.wordpress.com/" title="LOLcatz">LOLCatz</a> rules apply here:  &#8220;Using Rails to make your life easy - <a href="http://icanhascheezburger.com/2007/04/28/youre-doing-it-wrong-2/" title="you&#8217;re doing it wrong &laquo; Lolcats &#8216;n&#8217; Funny Pictures - I Can Has Cheezburger?">ur doin&#8217; it wrong</a>&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/rails-associations/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Me lately&#8230;</title>
		<link>http://stevengharms.com/me-lately</link>
		<comments>http://stevengharms.com/me-lately#comments</comments>
		<pubDate>Fri, 11 Jan 2008 22:13:41 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1085</guid>
		<description><![CDATA[Rails&#8230; &#8230;Lauren Rails&#8230; &#8230;work Rails&#8230; &#8230;school next week Rails&#8230; &#8230;Unicode Rails&#8230; &#8230;fingers hurt]]></description>
			<content:encoded><![CDATA[<p>Rails&#8230;<br />
&#8230;Lauren<br />
Rails&#8230;<br />
&#8230;work<br />
Rails&#8230;<br />
&#8230;school next week<br />
Rails&#8230;<br />
&#8230;Unicode<br />
Rails&#8230;<br />
&#8230;fingers hurt</p>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/me-lately/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Rails]  Cleaning up HABTM views (2/2)</title>
		<link>http://stevengharms.com/rails-cleaning-up-habtm-views-22</link>
		<comments>http://stevengharms.com/rails-cleaning-up-habtm-views-22#comments</comments>
		<pubDate>Fri, 11 Jan 2008 20:58:38 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1084</guid>
		<description><![CDATA[You may want to see the previous entry on this topic. We&#8217;ll be using that application. The reality is that most people use Rails for web frameworks &#8230; the console manipulation stuff we explored in the previous post doesn&#8217;t really help us much. We need a web interface. While using the script/generate gave us some [...]]]></description>
			<content:encoded><![CDATA[<p>You may want to see the <a href="http://stevengharms.net/?p=1083">previous entry on this topic</a>.  We&#8217;ll be using that application.</p>

<p>The reality is that most people use Rails for web frameworks &#8230; the console manipulation stuff we explored in the previous post doesn&#8217;t really help us much.  We need a web interface.  While using the script/generate gave us some scaffolds that we can play with ( http://localhost:3000/candies or ../flavors ), it&#8217;s not really &#8220;integrated&#8221; and it doesn&#8217;t quite demonstrate the &#8220;has many&#8221;-ness.</p>

<p>First we&#8217;ll fire up the web server (script/server) and see what the &#8216;new&#8217; view looks like:</p>

<p><a href="http://www.flickr.com/photos/sgharms/2186255566/" title="ss2. by sgharms, on Flickr"><img src="http://farm3.static.flickr.com/2178/2186255566_a22a3ff310.jpg" width="500" height="317" alt="ss2." /></a></p>

<p>Hm, that&#8217;s certainly not giving us any place to enter some flavorful information.  Let&#8217;s fix that in the view.</p>

<p><span id="more-1084"></span></p>

<pre>
    &lt;p&gt;
        &lt;b&gt;Flavors ( comma-delimited )&lt;/b&gt;&lt;br/&gt;
      &lt;%= f.text_field :flavorstring %&gt;
    &lt;/p&gt;
</pre>

<p>Try reloading the view&#8230;</p>

<p>And we get&#8230;an error:</p>

<p><a href="http://www.flickr.com/photos/sgharms/2186255722/" title="ss4 by sgharms, on Flickr"><img src="http://farm3.static.flickr.com/2306/2186255722_d121425a1b.jpg" width="500" height="317" alt="ss4" /></a></p>

<pre>
    Undefined method `flavorstring&#x27; for #&lt;Candy id: nil, name: nil, created_at: nil, updated_at: nil&gt;
</pre>

<p>What I&#8217;m effectively doing here is making us need to call a &#8220;virtual attribute&#8221;.  You see, what goes in here is the CGI code to generate a text field such that we can put in a comma-delimited list of flavors.  On the flip side, in other views, we&#8217;ll want to have &#8216;flavorstring&#8217; give us a comma-delimited listing of the associated flavors.</p>

<p>So, let&#8217;s add the virtual attribute into the app/models/candy.rb file:</p>

<pre>
  def flavorstring
     if (self.flavors.length &gt; 0)
       x=String.new()
       self.flavors.uniq.each do |f|
         x += f.name
         x += &quot;, &quot;
       end
       return x.sub(/,\s+$/,&#x27;&#x27;)
     else
       return &quot;&quot;
     end
     
   end
   
   def flavorstring=(input)
       if input.empty?
         self.flavors.destroy_all
       end
       
       self.flavors.destroy_all
       input.gsub(/\s+/, &#x27;&#x27;).split(&#x27;,&#x27;).uniq.each do |flav|
         if Flavor.find_by_name(flav).nil?
           self.flavors &lt;&lt; Flavor.create(:name=&gt; flav)
         else
           self.flavors &lt;&lt; Flavor.find_by_name(flav)
         end
       end
   end
</pre>

<p><a href="http://www.flickr.com/photos/sgharms/2185471781/" title="ss3 by sgharms, on Flickr"><img src="http://farm3.static.flickr.com/2230/2185471781_03138755e4.jpg" width="500" height="317" alt="ss3" /></a></p>

<p>It&#8217;s also handy to define the <code>to_s</code> method to return the &#8220;name&#8221; attribute of this model ( this should also be added to the Flavor model).  It means that if anyone executes something like <code>puts aCandy</code> or <code>puts aFlavor</code> they get the name of that item, versus something like &lt;Flavor:124124&gt;.</p>

<p>Reload the view and create some candies with your own tags&#8230;</p>

<p><a href="http://www.flickr.com/photos/sgharms/2185471969/" title="ss5 by sgharms, on Flickr"><img src="http://farm3.static.flickr.com/2304/2185471969_007eb9eb1a.jpg" width="500" height="325" alt="ss5" /></a></p>

<p>If you want to edit the flavors, you can do so by taking advantage of the scaffolds we created earlier:</p>

<p>http://localhost:3000/flavors</p>

<p>Because I&#8217;m sorta anal, i&#8217;m going to alphabetically sort my scaffolds.  I go to the &#8216;candies_controller&#8217; or &#8216;flavors_controller&#8217; and edit the &#8216;index&#8217; method to make my find command look like:</p>

<pre>
@candies = Candy.find(:all, <img src='http://stevengharms.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder=>'name asc')
</pre>

<p>Hey, looking at that index, it&#8217;s notably not showing our flavor data.  Let&#8217;s fix that.</p>

<p>Now, I know I can get a given Candy&#8217;s flavors by issuing <code>aCandy.flavors</code> which will come back as an array.  So what I would like to do is find a way to pass an array to a loop, have it assemble some sensible HTML, and then return it to me.  This will keep my view neat.</p>

<p>But I also know that, especially in a HABTM relationship, if I want something to work for one side, I&#8217;ll probably want it to work for the other side.  That is, if I want to get a comma-delimited list of flavors associated with a candy which are links to that flavor ( which should also show the candies associated with it) &mdash; I&#8217;ll also probably want the reverse, from the perspective of the flavors.</p>

<p>{Yeah, you may want to re-read that a few times }</p>

<p>So I&#8217;m going to write a &#8220;helper&#8221;.  I&#8217;m not going to put this in the candies_helper or in the flavors_helper.rb.  Because of the reflexivity ( Flavor &lt;-&gt; Candy ), I want to put this method into the application_helper.rb and make it sufficiently abstract so that it could be called either by a view associated with a Candy or with a Flavor.</p>

<pre>
  def link_to_comma_sep_elements(hash)
    html = &#x27;&#x27;
    hash[:ray].each do |x|
      puts x.class
      html &lt;&lt; link_to(x,:controller=&gt;hash[:controller],:action=&gt;hash[:action], :id=&gt;x.class.find(x.id))
      html &lt;&lt; &quot;, &quot;
    end
    return html.sub(/,\s+$/, &#x27;&#x27;)
  end
</pre>

<p>This means it can be called like so:</p>

<pre>
    &lt;%= link_to_comma_sep_elements(:ray=&gt;candy.flavors, :controller=&gt;&quot;flavors&quot;, :action=&gt;&quot;show&quot;) %&gt;
</pre>

<p>I pass an array to the function, a controller(&#8220;flavors&#8221;) that the comma-ized elements will want to point to and the action they should point to (&#8220;show&#8221;).</p>

<p><a href="http://www.flickr.com/photos/sgharms/2186255882/" title="ss6 by sgharms, on Flickr"><img src="http://farm3.static.flickr.com/2256/2186255882_d17b11259e.jpg" width="500" height="317" alt="ss6" /></a></p>

<p>But if i click on one of those flavors, I&#8217;m taken to a view of the flavor but without associated candy information.  Simple.  Add to app/view/flavors/show.html.erb:</p>

<pre>
    &lt;p&gt;
        &lt;b&gt;Associated Candies: &lt;/b&gt;
      &lt;%= link_to_comma_sep_elements(:ray=&gt;@flavor.candies, :controller=&gt;&quot;candies&quot;, :action=&gt;&quot;show&quot;) %&gt;
    &lt;/p&gt;
</pre>

<p>See!  Our helper is already saving is work!  Cool eh?</p>

<p>Now say we approach from the /flavors scaffold, what if we want to have a comma-delimited list of associated candies?  You guessed it, our helper to the rescue ( again! )</p>

<pre>
    &lt;table&gt;
      &lt;tr&gt;
        &lt;th&gt;Name&lt;/th&gt;
            &lt;th&gt;Candies&lt;/th&gt;
      &lt;/tr&gt;

    &lt;% for flavor in @flavors %&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;%=h flavor.name %&gt;&lt;/td&gt;
            &lt;td&gt;
              &lt;%= link_to_comma_sep_elements(:ray=&gt;flavor.candies, :controller=&gt;&quot;candies&quot;, :action=&gt;&quot;show&quot;) %&gt;
            &lt;/td&gt; 
        &lt;td&gt;&lt;%= link_to &#x27;Show&#x27;, flavor %&gt;&lt;/td&gt;
        &lt;td&gt;&lt;%= link_to &#x27;Edit&#x27;, edit_flavor_path(flavor) %&gt;&lt;/td&gt;
        &lt;td&gt;&lt;%= link_to &#x27;Destroy&#x27;, flavor, :confirm =&gt; &#x27;Are you sure?&#x27;, :method =&gt; :delete %&gt;&lt;/td&gt;
      &lt;/tr&gt;
    &lt;% end %&gt;
    &lt;/table&gt;  
</pre>

<p>Now at this point you have a pretty functional setup.  To make playing with and exploring your HABTM relationship a bit easier, I added links at the bottom of each model&#8217;s index view so that you could flip between the two.</p>

<p>Flavor&#8217;s index:  &lt;%= link_to &#x27;See Candies&#x27;, &quot;candies&quot;, :action=&gt;&#x27;index&#x27; %&gt;</p>

<p>Candy&#8217;s index:  &lt;%= link_to &#x27;See Flavors&#x27;, &quot;flavors&quot;, :action=&gt;&#x27;index&#x27; %&gt;</p>

<p>Try it out, experiment, and have fun. And write tutorials!  Writing is the best way to learn!  Us Rails-ers have to stick together!</p>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/rails-cleaning-up-habtm-views-22/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>[Rails]:  Steven&#8217;s Guide to: &#8220;Many to Many Associations&#8221; or &#8220;HABTM&#8221; (1/2)</title>
		<link>http://stevengharms.com/rails-stevens-guide-to-many-to-many-associations-or-habtm-12</link>
		<comments>http://stevengharms.com/rails-stevens-guide-to-many-to-many-associations-or-habtm-12#comments</comments>
		<pubDate>Fri, 11 Jan 2008 20:15:39 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1083</guid>
		<description><![CDATA[The concept: &#8220;Many to Many&#8221; relationships Many things in this life have a one to one relationship: a man has a wife ( Utah excepted ), a car has an owner, a dog it&#8217;s day. Many other things in life have a one to many relationship: a policy covers many people, a manager has direct [...]]]></description>
			<content:encoded><![CDATA[<h2>The concept:  &#8220;Many to Many&#8221; relationships</h2>

<p>Many things in this life have a one to one relationship: a man has a wife ( Utah excepted ), a car has an owner, a dog it&#8217;s day.  Many other things in life have a one to many relationship:  a policy covers many people, a manager has direct reports, etc.  But some things have a many to many relationship.  People have surnames (&#8220;John Smith&#8221; is a Smith and so is &#8220;Jane Smith&#8221;;conversely, among the Smith clan there might be multiple Johns, 42 Janes, and 22 Larry&#8217;s ).</p>

<p>It is of this many to many relationship I will write and whose code I seek to share.</p>

<p>In this world there are many candies ( &#8220;Now and Laters&#8221;, &#8220;Sweet Tarts&#8221;, and &#8220;<a href="http://stevengharms.net/?p=383">Kasugai&#8217;s Gummies</a>&#8221; ) and candies have a flavor (chocolate, strawberry, cherry, and for my readers of an Oriental persuasion, lychee).</p>

<p>There are many candies which have a flavor, and a particular flavor has many candies which apply to it.  This is a perfect, and simple example wherewith to demonstrate Rails&#8217; ActiveRecord&#8217;s Associations.</p>

<p><span id="more-1083"></span></p>

<h2>Build the Rails install directory</h2>

<p>So, let&#8217;s start a rails project:</p>

<p><code>rails -d postgresql candy</code></p>

<p>And you will get a great deal of noise back:</p>

<pre>
create  
create  app/controllers
create  app/helpers
create  app/models
create  app/views/layouts
create  config/environments
create  config/initializers
create  db
create  doc
create  lib
create  lib/tasks
create  log
create  public/images
create  public/javascripts
create  public/stylesheets
create  script/performance
create  script/process
create  test/fixtures
create  test/functional
create  test/integration
create  test/mocks/development
create  test/mocks/test
create  test/unit
create  vendor
create  vendor/plugins
create  tmp/sessions
create  tmp/sockets
create  tmp/cache
create  tmp/pids
create  Rakefile
create  README
create  app/controllers/application.rb
create  app/helpers/application_helper.rb
create  test/test_helper.rb
create  config/database.yml
create  config/routes.rb
create  public/.htaccess
create  config/initializers/inflections.rb
create  config/initializers/mime_types.rb
create  config/boot.rb
create  config/environment.rb
create  config/environments/production.rb
create  config/environments/development.rb
create  config/environments/test.rb
create  script/about
create  script/console
create  script/destroy
create  script/generate
create  script/performance/benchmarker
create  script/performance/profiler
create  script/performance/request
create  script/process/reaper
create  script/process/spawner
create  script/process/inspector
create  script/runner
create  script/server
create  script/plugin
create  public/dispatch.rb
create  public/dispatch.cgi
create  public/dispatch.fcgi
create  public/404.html
create  public/422.html
create  public/500.html
create  public/index.html
create  public/favicon.ico
create  public/robots.txt
create  public/images/rails.png
create  public/javascripts/prototype.js
create  public/javascripts/effects.js
create  public/javascripts/dragdrop.js
create  public/javascripts/controls.js
create  public/javascripts/application.js
create  doc/README_FOR_APP
create  log/server.log
create  log/production.log
create  log/development.log
create  log/test.log
</pre>

<p>Now, let&#8217;s imagine a &#8220;Candy&#8221;, it has a &#8220;name&#8221;.  Similarly a &#8220;Flavor&#8221; has a &#8220;name&#8221;.  These two will be our models.  We&#8217;ll use Rails&#8217; <a href="">new scaffolding</a> to create these models.</p>

<h2>Build the Candy and Flavor models</h2>

<pre>
bash-3.2$ cd candy/
bash-3.2$ script/generate scaffold Candy name:string; \
  script/generate scaffold Flavor name:string
</pre>

<p><em>Output not displayed</em></p>

<h2>Create the database</h2>

<pre>
bash-3.2$ psql -l |grep -i candy
bash-3.2$ rake db:create
(in /Users/sgharms/railsdev/candy)
bash-3.2$ psql -l |grep -i candy
 candy_development           | sgharms  | UTF8
</pre>

<p>OK, so there&#8217;s our database.  Since I don&#8217;t want to have to create a user record, I&#8217;m going to edit my config/database.yml to make connections to the database anonyomous.  I&#8217;m going to remove the user and password fields.</p>

<pre>
>development:
>adapter: postgresql
>encoding: unicode
>database: candy_development
>#  username: candy
>#  password:
</pre>

<h2>Use db:migrate to bring the generated models into the db</h2>

<pre>
bash-3.2$ rake db:migrate
(in /Users/sgharms/railsdev/candy)
== 1 CreateCandies: migrating =========================================
-- create_table(:candies)
NOTICE:  CREATE TABLE will create implicit sequence &quot;candies_id_seq&quot; 
for serial column &quot;candies.id&quot;
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index 
&quot;candies_pkey&quot; for table &quot;candies&quot;     -&gt; 0.0097s
== 1 CreateCandies: migrated (0.0099s) ================================

== 2 CreateFlavors: migrating =========================================
-- create_table(:flavors)
NOTICE:  CREATE TABLE will create implicit sequence &quot;flavors_id_seq&quot; 
for serial column &quot;flavors.id&quot;
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index 
    &quot;flavors_pkey&quot; for table &quot;flavors&quot;
== 2 CreateFlavors: migrated (0.0071s) ================================
</pre>

<p>So far so good!  Let&#8217;s check out the tables.</p>

<h2>Examine the tables with Psql, the Postgres CLI tool</h2>

<p>Logically enough, a table for holding &#8220;Candy&#8221;-model based objects and &#8220;Flavor&#8221;-based objects were created.  A simple SQL query shows the contents to match our expectation.</p>

<pre>
    bash-3.2$ psql candy_development
    Welcome to psql 8.2.5, the PostgreSQL interactive terminal.

    Type:  \copyright for distribution terms
           \h for help with SQL commands
           \? for help with psql commands
           \g or terminate with semicolon to execute query
           \q to quit

    candy_development=# \dt
               List of relations
     Schema |    Name     | Type  |  Owner  
    --------+-------------+-------+---------
     public | candies     | table | sgharms
     public | flavors     | table | sgharms
     public | schema_info | table | sgharms
    (3 rows)

    candy_development=# select * from CANDIES, flavors;
     id | name | created_at | updated_at | id | name 
    ----+------+------------+------------+----+------
    (0 rows)
</pre>

<p>Well that&#8217;s pretty nifty, no entries.</p>

<h2>Create the HABTM relationship</h2>

<p>Now, we need to make a change to the model.  We need to make both of these models recognize the other as a HABTM partner.  Simple enough, add these line to &#8220;candy.rb&#8221; and &#8220;flavor.rb&#8221; in app/models/, respectively:</p>

<blockquote>
  <p>has_and_belongs_to_many :flavors<br />
   has_and_belongs_to_many :candies</p>
</blockquote>

<p>You may be wondering if the plural of &#8220;candy&#8221; was &#8220;candys&#8221; or &#8220;candies&#8221; in Rails&#8217; eyes.  Let&#8217;s check that out.</p>

<pre>
bash-3.2$ script/console 
Loading development environment (Rails 2.0.2)
&gt;&gt; &quot;candy&quot;.pluralize
=&gt; &quot;candies&quot;
</pre>

<p>Since we scaffolded these views when we created the model, let&#8217;s try adding a Candy.</p>

<p>Start the server:</p>

<pre>
    &gt;&gt; bash-3.2$ script/server
    =&gt; Booting Mongrel (use &#x27;script/server webrick&#x27; to force WEBrick)
    =&gt; Rails application starting on http://0.0.0.0:3000
    =&gt; Call with -d to detach
    =&gt; Ctrl-C to shutdown server
    ** Starting Mongrel listening at 0.0.0.0:3000
    ** Starting Rails with development environment...
    ** Rails loaded.
    ** Loading any Rails specific GemPlugins
    ** Signals ready.  TERM =&gt; stop.  USR2 =&gt; restart.  
    INT =&gt; stop (no restart).
    ** Rails signals registered.  HUP =&gt; reload (without restart). 
     It might not work well.
    ** Mongrel 1.1.2 available at 0.0.0.0:3000
    ** Use CTRL-C to stop.
</pre>

<p>And visit http//localhost:3000/candies</p>

<p>You should have a basic scaffold view that you can create candies with.</p>

<p><a href="http://www.flickr.com/photos/sgharms/2186255566/" title="ss2. by sgharms, on Flickr"><img src="http://farm3.static.flickr.com/2178/2186255566_a22a3ff310.jpg" width="500" height="317" alt="ss2." /></a></p>

<p>I added two candies and back in the console I could see&#8230;</p>

<pre>
    &gt;&gt; puts Candy.find(:all).to_yaml
    --- 
    - !ruby/object:Candy 
      attributes: 
        name: PowerThirst Bar
        updated_at: 2008-01-10 18:26:22.882081
        id: "1"
        created_at: 2008-01-10 18:26:22.882081
      attributes_cache: {}

    - !ruby/object:Candy 
      attributes: 
        name: Sweet Tart
        updated_at: 2008-01-10 18:26:38.846037
        id: "2"
        created_at: 2008-01-10 18:26:38.846037
      attributes_cache: {}
</pre>

<p>The Web UI shows:</p>

<p><a href="http://www.flickr.com/photos/sgharms/2185471687/" title="ss1 by sgharms, on Flickr"><img src="http://farm3.static.flickr.com/2316/2185471687_e6ba425344.jpg" width="500" height="317" alt="ss1" /></a></p>

<p>Similarly one can create flavors using the scaffold as well, but in this case I&#8217;ll use the console:</p>

<pre>
    &gt;&gt; Flavor
    =&gt; Flavor(id: integer, name: string, created_at: datetime, updated_at: datetime)
    &gt;&gt; Flavor.create :name=&gt;&quot;Shockolate&quot;
    =&gt; #&lt;Flavor id: 1, name: &quot;Shockolate&quot;, created_at: &quot;2008-01-10 18:30:13&quot;, updated_at: &quot;2008-01-10 18:30:13&quot;&gt;
    &gt;&gt; Flavor.create :name=&gt;&quot;Rawberry&quot;
    =&gt; #&lt;Flavor id: 2, name: &quot;Rawberry&quot;, created_at: &quot;2008-01-10 18:30:17&quot;, updated_at: &quot;2008-01-10 18:30:17&quot;&gt;
    &gt;&gt; Flavor.create :name=&gt;&quot;Lychee&quot;
    =&gt; #&lt;Flavor id: 3, name: &quot;Lychee&quot;, created_at: &quot;2008-01-10 18:30:34&quot;, updated_at: &quot;2008-01-10 18:30:34&quot;&gt;
    &gt;&gt; Flavor.create :name=&gt;&quot;Strawberry&quot;
    =&gt; #&lt;Flavor id: 4, name: &quot;Strawberry&quot;, created_at: &quot;2008-01-10 18:30:38&quot;, updated_at: &quot;2008-01-10 18:30:38&quot;&gt;
    &gt;&gt; Flavor.find_all  
    NoMethodError: undefined method `find_all&#x27; for #&lt;Class:0x1b60c3c&gt;
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.0.2-/lib/active_record/base.rb:1532:in `method_missing&#x27;
        from (irb):7
    &gt;&gt; Flavor.find(:all)
    =&gt; [#&lt;Flavor id: 1, name: &quot;Shockolate&quot;, created_at: &quot;2008-01-10 18:30:13&quot;, updated_at: &quot;2008-01-10 18:30:13&quot;&gt;, #&lt;Flavor id: 2, name: &quot;Rawberry&quot;, created_at: &quot;2008-01-10 18:30:17&quot;, updated_at: &quot;2008-01-10 18:30:17&quot;&gt;, #&lt;Flavor id: 3, name: &quot;Lychee&quot;, created_at: &quot;2008-01-10 18:30:34&quot;, updated_at: &quot;2008-01-10 18:30:34&quot;&gt;, #&lt;Flavor id: 4, name: &quot;Strawberry&quot;, created_at: &quot;2008-01-10 18:30:38&quot;, updated_at: &quot;2008-01-10 18:30:38&quot;&gt;]
</pre>

<p>You can take a look at your database schema in db/schema.rb:</p>

<pre>
ActiveRecord::Schema.define(:version => 2) do

  create_table "candies", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "flavors", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end
</pre>

<h2>Create a join table</h2>

<p>Now, a HABTM requires a join table, so that the two can look back and forth at one anotherthat&#8217;s fancy-talk for a two-way index between these two tables.</p>

<p>The convention that we use is to create a table, that has no primary key, that has the consituentModelNameOne_id as one column and consituentModelNameTwo_id as the other column.  When I say &#8216;constituentModelName&#8217; that should be in the singular.  Also, the name of the table should list the plural of the two models, separated by an underscore &quot;_&quot; with the plurals in alphabetical order.  In our case this would be &#8220;candies_flavors&#8221;</p>

<p>This sounds hairy, but I&#8217;ll show you.  It&#8217;s really easy.</p>

<p>&lt;</p>

<p>pre>
bash-3.2$ script/generate migration createCandyFlavorJoinTable
      exists  db/migrate
      create  db/migrate/003_create_candy_flavor_join_table.rb
bash-3.2$</p>

<p>&lt;</p>

<p>pre></p>

<p>Excellent!  So now let&#8217;s create that table.  If you forget the syntax, you can look at your 001 or 002 migration in db/migrate to learn how to create a table.</p>

<pre>
    class CreateCandyFlavorJoinTable &lt; ActiveRecord::Migration
      def self.up
        create_table (:candies_flavors, :id=&gt;false) do |t|
          t.integer :candy_id
          t.integer :flavor_id

          t.timestamps
        end
      end

      def self.down
        drop_table :candies_flavors
      end
    end
</pre>

<p>Great!  All we need to do is use another visit to rake.</p>

<pre>
bash-3.2$ rake db:migrate
(in /Users/sgharms/railsdev/candy)
== 3 CreateCandyFlavorJoinTable: migrating ====================================
-- create_table(:candies_flavors, {:id=>false})
   -> 0.0049s
== 3 CreateCandyFlavorJoinTable: migrated (0.0051s) ===========================
</pre>

<p>We can check it out in the Postgres viewer:</p>

<pre>
candy_development=# select * from candies_flavors ;
 candy_id | flavor_id | created_at | updated_at 
----------+-----------+------------+------------
(0 rows)
</pre>

<p>So now let&#8217;s associate a candy with a flavor.</p>

<p>See what we have</p>

<pre>&gt;&gt; Candy.find(:all)
=&gt; [#&lt;Candy id: 1, name: &quot;PowerThirst Bar&quot;, created_at: &quot;2008-01-10 18:26:22&quot;, updated_at: &quot;2008-01-10 18:26:22&quot;&gt;, #&lt;Candy id: 2, name: &quot;Sweet Tart&quot;, created_at: &quot;2008-01-10 18:26:38&quot;, updated_at: &quot;2008-01-10 18:26:38&quot;&gt;]
&gt;&gt; Flavor.find(:all)
=&gt; [#&lt;Flavor id: 1, name: &quot;Shockolate&quot;, created_at: &quot;2008-01-10 18:30:13&quot;, updated_at: &quot;2008-01-10 18:30:13&quot;&gt;, #&lt;Flavor id: 2, name: &quot;Rawberry&quot;, created_at: &quot;2008-01-10 18:30:17&quot;, updated_at: &quot;2008-01-10 18:30:17&quot;&gt;, #&lt;Flavor id: 3, name: &quot;Lychee&quot;, created_at: &quot;2008-01-10 18:30:34&quot;, updated_at: &quot;2008-01-10 18:30:34&quot;&gt;, #&lt;Flavor id: 4, name: &quot;Strawberry&quot;, created_at: &quot;2008-01-10 18:30:38&quot;, updated_at: &quot;2008-01-10 18:30:38&quot;&gt;]</pre>

<p>Note that you can now ask a Candy what it&#8217;s &#8216;flavors&#8217; are - with tab-autocomplete:</p>

<pre>&gt;&gt; Candy.find(1).fla(TAB)(TAB)vor(TAB)(TAB)
1).flavor_ids    1).flavor_path   1).flavors       1).flavors_path
1).flavor_ids=   1).flavor_url    1).flavors=      1).flavors_url
&gt;&gt; Candy.find(1).flavors
=&gt; []</pre>

<p>Similarly, a flavor can be asked its candies:</p>

<pre>&gt;&gt; Flavor.find_by_name(&#x27;Shockolate&#x27;).candies
=&gt; []</pre>

<p>Let&#8217;s associate &#8216;Shockolate&#8217; and &#8216;Rawberry&#8217; with a PowerThirst Bar</p>

<pre>
&gt;&gt; example.flavors
=&gt; []
&gt;&gt; example.flavors &lt;&lt; Flavor.find_by_name(&#x27;Shockolate&#x27;)
=&gt; [#&lt;Flavor id: 1, name: &quot;Shockolate&quot;, created_at: &quot;2008-01-10 18:30:13&quot;, updated_at: &quot;2008-01-10 18:30:13&quot;&gt;]
    &gt;&gt; example.flavors &lt;&lt; Flavor.find_by_name(&#x27;Rawberry&#x27;)
    =&gt; [#&lt;Flavor id: 1, name: &quot;Shockolate&quot;, created_at: &quot;2008-01-10 18:30:13&quot;, updated_at: &quot;2008-01-10 18:30:13&quot;&gt;, #&lt;Flavor id: 2, name: &quot;Rawberry&quot;, created_at: &quot;2008-01-10 18:30:17&quot;, updated_at: &quot;2008-01-10 18:30:17&quot;&gt;]
    &gt;&gt; example.flavors
    =&gt; [#&lt;Flavor id: 1, name: &quot;Shockolate&quot;, created_at: &quot;2008-01-10 18:30:13&quot;, updated_at: &quot;2008-01-10 18:30:13&quot;&gt;, #&lt;Flavor id: 2, name: &quot;Rawberry&quot;, created_at: &quot;2008-01-10 18:30:17&quot;, updated_at: &quot;2008-01-10 18:30:17&quot;&gt;]</pre>

<p>Let&#8217;s see what&#8217;s happened in the DB.</p>

<pre>candy_development=# SELECT * from candies_flavors ;
 candy_id | flavor_id |         created_at         |         updated_at         
----------+-----------+----------------------------+----------------------------
        1 |         1 | 2008-01-10 18:30:13.002001 | 2008-01-10 18:30:13.002001
        1 |         2 | 2008-01-10 18:30:17.905373 | 2008-01-10 18:30:17.905373
(2 rows)
</pre>

<p>Unsurprisingly candy 1 (Candy.find(1).name) is associated with flavor id 1 and 2 ( Shockolate and Rawberry, respectively).</p>

<p>Sweet (ur, Shockolate-y?).  We have a 1 to many relationship now (&#8220;The name &#8220;PowerThirst Bar&#8221; corresponds two two flavors: Shockolate and Rawberry&#8221;).  But we want those to also work in reverse.  That we could get all the candies that are flavored, say with good old &#8220;Strawberry&#8221;.  To the console!</p>

<p>Add another candy</p>

<pre>
&gt;&gt; Candy.create :name=&gt;&quot;Now and Later&quot;
=&gt; #&lt;Candy id: 3, name: &quot;Now and Later&quot;, created_at: &quot;2008-01-10 19:02:35&quot;, updated_at: &quot;2008-01-10 19:02:35&quot;&gt;   
</pre>

<p>Now let&#8217;s associate a few candies with &#8216;Strawberry&#8217; flavor.  I&#8217;m going to include the PowerThirst bar because Rawberry is a subclass of Strawberry.</p>

<pre>
    &gt;&gt; strawberry=Flavor.find_by_name(&#x27;Strawberry&#x27;)
    =&gt; #&lt;Flavor id: 4, name: &quot;Strawberry&quot;, created_at: &quot;2008-01-10 18:30:38&quot;, updated_at: &quot;2008-01-10 18:30:38&quot;&gt;
    &gt;&gt; strawberry.name
    =&gt; &quot;Strawberry&quot;
    &gt;&gt; strawberry.candies
    =&gt; []
    &gt;&gt; strawberry.candies &lt;&lt; Candy.find(1,2,3)
    =&gt; [#&lt;Candy id: 1, name: &quot;PowerThirst Bar&quot;, created_at: &quot;2008-01-10 18:26:22&quot;, updated_at: &quot;2008-01-10 18:26:22&quot;&gt;, #&lt;Candy id: 2, name: &quot;Sweet Tart&quot;, created_at: &quot;2008-01-10 18:26:38&quot;, updated_at: &quot;2008-01-10 18:26:38&quot;&gt;, #&lt;Candy id: 3, name: &quot;Now and Later&quot;, created_at: &quot;2008-01-10 19:02:35&quot;, updated_at: &quot;2008-01-10 19:02:35&quot;&gt;]
    &gt;&gt; strawberry.candies
    =&gt; [#&lt;Candy id: 1, name: &quot;PowerThirst Bar&quot;, created_at: &quot;2008-01-10 18:26:22&quot;, updated_at: &quot;2008-01-10 18:26:22&quot;&gt;, #&lt;Candy id: 2, name: &quot;Sweet Tart&quot;, created_at: &quot;2008-01-10 18:26:38&quot;, updated_at: &quot;2008-01-10 18:26:38&quot;&gt;, #&lt;Candy id: 3, name: &quot;Now and Later&quot;, created_at: &quot;2008-01-10 19:02:35&quot;, updated_at: &quot;2008-01-10 19:02:35&quot;&gt;]    
</pre>

<p>So there you have it.  You can see the structure beautifully with the .to_yaml method:</p>

<pre>
    &gt;&gt; puts strawberry.to_yaml
    --- !ruby/object:Flavor 
    attributes: 
      name: Strawberry
      updated_at: 2008-01-10 18:30:38.250826
      id: &quot;4&quot;
      created_at: 2008-01-10 18:30:38.250826
    attributes_cache: {}

    candies: 
    - !ruby/object:Candy 
      attributes: 
        name: PowerThirst Bar
        updated_at: 2008-01-10 18:26:22.882081
        id: &quot;1&quot;
        created_at: 2008-01-10 18:26:22.882081
      attributes_cache: {}

    - !ruby/object:Candy 
      attributes: 
        name: Sweet Tart
        updated_at: 2008-01-10 18:26:38.846037
        id: &quot;2&quot;
        created_at: 2008-01-10 18:26:38.846037
      attributes_cache: {}

    - !ruby/object:Candy 
      attributes: 
        name: Now and Later
        updated_at: 2008-01-10 19:02:35.926161
        id: &quot;3&quot;
        created_at: 2008-01-10 19:02:35.926161
      attributes_cache: {}

    =&gt; nil

</pre>

<p>Or&#8230;.</p>

<pre>
    &gt;&gt; puts Candy.find(1).flavors.to_yaml
    --- 
    - !ruby/object:Flavor 
      attributes: 
        name: Shockolate
        updated_at: 2008-01-10 18:30:13.002001
        id: &quot;1&quot;
        flavor_id: &quot;1&quot;
        candy_id: &quot;1&quot;
        created_at: 2008-01-10 18:30:13.002001
      attributes_cache: {}

      readonly: true
    - !ruby/object:Flavor 
      attributes: 
        name: Rawberry
        updated_at: 2008-01-10 18:30:17.905373
        id: &quot;2&quot;
        flavor_id: &quot;2&quot;
        candy_id: &quot;1&quot;
        created_at: 2008-01-10 18:30:17.905373
      attributes_cache: {}

      readonly: true
    - !ruby/object:Flavor 
      attributes: 
        name: Strawberry
        updated_at: 2008-01-10 18:26:22.882081
        id: &quot;4&quot;
        flavor_id: &quot;4&quot;
        candy_id: &quot;1&quot;
        created_at: 2008-01-10 18:26:22.882081
      attributes_cache: {}

      readonly: true
    =&gt; nil
</pre>

<p>With this in shape, we are able to manipulate the tables and the model via the script/console.  We next need to beef-up the views &mdash; but that&#8217;s for the next installment!</p>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/rails-stevens-guide-to-many-to-many-associations-or-habtm-12/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rails and Unicode and PostGres DB (Oh My!):  Understanding how UTF-8 works</title>
		<link>http://stevengharms.com/rails-and-unicode-and-postgres-db-oh-my-trying-understand-how-unicode-characters-get-entered</link>
		<comments>http://stevengharms.com/rails-and-unicode-and-postgres-db-oh-my-trying-understand-how-unicode-characters-get-entered#comments</comments>
		<pubDate>Sat, 05 Jan 2008 20:12:48 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology and Computers]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1082</guid>
		<description><![CDATA[Examine the Unicode standard&#8217;s code page collection for &#8220;Latin small letter a with macron&#8221;. Nets U0100.pdf &#8220;Latin small letter a with macron&#8221; appears on chart as 0101. This is a hexidemial number which points to U+0101 as its code point. Converting 0101 to decimal gets you 257, this is the same as the HTML entity [...]]]></description>
			<content:encoded><![CDATA[<ol>
<li><p>Examine the <a href="http://unicode.org/standard/standard.html" title="Unicode Standard">Unicode standard&#8217;s</a> code page collection for &#8220;Latin small letter a with macron&#8221;.</p></li>
<li><p>Nets U0100.pdf</p></li>
<li><p>&#8220;Latin small letter a with macron&#8221; appears on chart as 0101.  This is a hexidemial number which points to U+0101 as its code point.  Converting 0101 to decimal gets you 257, this is the same as the HTML entity code.  Thus one can enter either &amp;#257; or &amp;amp#x0101; and get the right glyph [&#257;|&#x0101;]</p></li>
<li><p>Put &#257; character into a view via Rails that is back-ended by a PostGres database.</p></li>
<li><p>Using script/console, write the collection of models that contain this accented character to a YAML file.</p></li>
<li><p>&#8220;Latin small letter a with macron&#8221; is stored in a YAML dump of accented charcters as:  \xC4\x81</p></li>
<li><p>Hm, OK that&#8217;s a start.  Somehow 0101 or 257 is linked to C4 81.  How?   I know, BTW, the database that holds that entry is in UTF-8 as <code>psql -l</code> shows this.</p></li>
<li><p>C4:  196</p></li>
<li><p>81:   129</p></li>
<li><p>196+129=325  != 0101.  Hm, look at documentation.</p></li>
<li><p>Be stumped.</p></li>
<li><p>Send mail to mailing lists for help.</p></li>
</ol>


<hr />


<p><em>In the immortal words of <a href="http://www.civ3.com/" title="Civilization III: Home">Sid Meier&#8217;s &#8220;Civilization&#8221;</a>:  &#8220;Time Passes&#8230;&#8221;</em></p>


<hr />


<ol>
<li><p>\xC4\x81 is the UTF-8 encoding for the Unicode code point U+0101.</p></li>
<li><p>[Q:]  Which table does U+0101 fall into?  <br/><br/>[A:]  &#8220;So the first 128 characters (US-ASCII) need one byte. The next 1920 characters need two bytes to encode. This includes Latin alphabet characters with diacritics, Greek, Cyrillic, Coptic, Armenian, Hebrew, and Arabic characters. The rest of the BMP characters use three bytes, and additional characters are encoded in four bytes.&#8221;</p></li>
<li><p>OK this means that the code point will be of the form:  &#8220;<strong>110</strong><em>yyyyy</em> <strong>10</strong><em>zzzzzz</em>&#8221;</p></li>
<li><p>We will now work to fill in the &#8220;y&#8221; and &#8220;z&#8221; values:</p></li>
<li><p>Hexidecimal &#8220;U+0101&#8221; converts to binary:  &#8220;<em>100000001</em>&#8221;</p></li>
<li><p>There are 5 y&#8217;s and 6 z&#8217;s.  So let&#8217;s split the above number to match that form: &#8220;<em>[00]100-000001</em>&#8221;.  Note, we moved from the right.  Where the leading 0&#8217;s were required to turn 100 into 00100, they were pre-pended.</p></li>
<li><p>Integrate and produce:  &#8220;<strong>110</strong>&#8221; + &#8220;<em>00100</em>&#8221; : &#8220;<strong>10</strong>&#8221; + &#8220;<em>000001</em>&#8221; => 11000100 : 10000001</p></li>
<li><p>Take THESE numbers and convert them <strong>back</strong> to hex => c4 81</p></li>
<li><p>String notation for this is \xc4\x81 - viol&aacute;!</p></li>
<li><p>Figuring this out letter by letter is a major pain in the keester.  A good URL resource is:  <a href="http://www.fileformat.info/info/unicode/">Fileformat.info</a> or, handily a URI of the form:</p></li>
</ol>

<pre>http://www.fileformat.info/info/unicode/char/&lt;unicode char value&gt;/index.htm</pre>

<p><em>Special Thanks to:  Michael Flester</em></p>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/rails-and-unicode-and-postgres-db-oh-my-trying-understand-how-unicode-characters-get-entered/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Rails]:  Is script/console not doing what you expect?</title>
		<link>http://stevengharms.com/rails-is-script-console-not-doing-what-you-expect</link>
		<comments>http://stevengharms.com/rails-is-script-console-not-doing-what-you-expect#comments</comments>
		<pubDate>Sat, 05 Jan 2008 04:17:16 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1081</guid>
		<description><![CDATA[This is more of a reminder to me for when I bang my head against the wall often and hard &#62;&#62;reload! Changes introduced by rake db:migrate and other tools will not be integrated into the console environment until you reload!]]></description>
			<content:encoded><![CDATA[<p><em>This is more of a reminder to me for when I bang my head against the wall often and hard</em></p>

<p><code>&gt;&gt;reload!</code></p>

<p>Changes introduced by <code>rake db:migrate</code> and other tools <em>will not be integrated into the console environment until you reload!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/rails-is-script-console-not-doing-what-you-expect/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails: Loading test data with fixtures</title>
		<link>http://stevengharms.com/rails-loading-test-data-with-fixtures</link>
		<comments>http://stevengharms.com/rails-loading-test-data-with-fixtures#comments</comments>
		<pubDate>Sat, 05 Jan 2008 00:47:09 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1080</guid>
		<description><![CDATA[Rails canonical story is: &#8220;Fixtures are used to load sample data before a unit test&#8221;. &#8220;Migrations are used to build DB tables and alter structure of contents thereof ( e.g., delete the &#8220;name&#8221; column and split the field on comma and put the resultant entries into the &#8220;firstname&#8221; column and the &#8220;lastname&#8221; column )&#8221; But [...]]]></description>
			<content:encoded><![CDATA[<p>Rails canonical story is:</p>

<ul>
<li>&#8220;Fixtures are used to load sample data before a unit test&#8221;.</li>
<li>&#8220;Migrations are used to build DB tables and alter structure of contents thereof ( e.g., delete the &#8220;name&#8221; column and split the field on comma and put the resultant entries into the &#8220;firstname&#8221; column and the &#8220;lastname&#8221; column )&#8221;</li>
</ul>

<p>But what if you need to bring in some good data &#8212; not test data, but data that you want for testing and seeing how things look with a &#8220;real&#8221; data set?  What then smarties?</p>

<p>Here was my situation:  I had entered data via the scaffolded interface and the the data included many unicode characters (&#038;258;&eacute;&aelig;, etc.).  I wrote a little JavaScript table <em>specifically</em> to make entering these characters easy from an English keyboard.</p>

<p>I knew that I was going to invariably mess up the data and wanted to have the ability to get this preliminary data set back in ( it&#8217;s just safer that way ).</p>

<p>Furthermore the datas contained Unicode and I&#8217;ve just not had time to wrap my head around &#8220;entering Unicode values via command line into  <a href="http://www.postgresql.org/" title="PostgreSQL: 
The world's most advanced open source database">PostGres</a>.</p>

<p>I dumped the data to a YML file with:</p>

<pre>
[code lang="ruby"]
x=File.open("models.yml")  
x.puts Model.find(:all).to\_yaml  
x.close  
[/code]
</pre>

<p>Looking at that Yaml data, I have my records.</p>

<p>I put that information into ../test/fixtures/models.yml</p>

<p>This file requires a bit of editing.</p>

<p>You will start with entries that look like:</p>

<pre>
    - !ruby/object:Model 
      attributes: 
        updated_at: 2008-01-04 19:32:10.874607
        id: "5"
        classification: Fourth
        created_at: 2008-01-04 19:32:10.874607
      attributes_cache: {}
</pre>

<p>You want to turn this into&#8230;.</p>

<pre>
first:
  updated_at: 2008-01-04 19:32:10.874607
  id: "5"
  classification: Fourth
</pre>

<p>That is, reduce the indents of the &#8220;meaty data&#8221;, remove the &#8220;- !ruby&#8221; declaration and then put a numbering tag ( &#8220;first&#8221; ).  This will help you import.  You may find it handy to try the following in the console:</p>

<pre>
[code lang="ruby"]
directory="./test/fixtures"
require 'active_record/fixtures'
Fixtures::create_fixtures( directory, "models")
Conjugation.find(:all)
[/code]
</pre>

<p>Obviously, good data here is a good sign; errors, a sign of more work.</p>

<p>Then with <code>rake db:load:fixtures</code> I could get my data back in&#8230;.but I wanted to make this addition hinge on a migration, so that I could move forward and backwards in the migration queue.  Thanks to the skateboard book p.273 I found a way.</p>

<p>First I created a migration <code>script/generate migration importBaselineData</code></p>

<p>Edit the <code>0xx_import_baseline_data.rb</code></p>

<pre>
[code lang="ruby"]
require 'active_record/fixtures'  
  
class LoadSampleData < ActiveRecord::Migration  
  def self.up  
    directory = File.join(File.dirname(__FILE__), "../../test/fixtures")  
    Fixtures::create_fixtures( directory, "models")  
  end  
  
  def self.down  
    Model.delete_all  
  end  
end  
[/code]
</pre>

<p>Thus with a <code>rake db:migrate</code> my migration with data entry gets entered.</p>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/rails-loading-test-data-with-fixtures/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scaffolding has changed in Rails 2.0:  Has it become un-Agile?</title>
		<link>http://stevengharms.com/scaffolding-has-changed-in-rails-20-has-it-become-un-agile</link>
		<comments>http://stevengharms.com/scaffolding-has-changed-in-rails-20-has-it-become-un-agile#comments</comments>
		<pubDate>Wed, 02 Jan 2008 18:26:20 +0000</pubDate>
		<dc:creator>steven</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Technology and Computers]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[wtf]]></category>

		<guid isPermaLink="false">http://stevengharms.net/?p=1065</guid>
		<description><![CDATA[This is the mail that I sent to Rails-list which describes my issues around the Rails scaffolding in Rails 2.0. Extensive debugging information can be found in my diagnostic research post. Hello, I&#8217;ve read the (many) re-posts about problems around scaffolding in Rails 2.0 and have followed a number of tutorials and fully understand &#8220;how [...]]]></description>
			<content:encoded><![CDATA[<p><em>This is the mail that I sent to Rails-list which describes my issues around the Rails scaffolding in Rails 2.0.  Extensive debugging information can be found in my <a href="http://stevengharms.net/?p=1063">diagnostic research post</a>.</em>

<hr />
</p>

<p>Hello,</p>

<p>I&#8217;ve read the (many) re-posts about problems around scaffolding in Rails 2.0 and have followed a number of tutorials and fully understand &#8220;how to scaffold&#8221; from a technical perspective, but  I don&#8217;t understand the <em>mindset</em> of how to use the new scaffolding.  It seems like a productivity- / agility- regress and I&#8217;m thinking I may have failed to properly grok the new setup.  In the interest of full disclosure, I&#8217;m coming back to Rails after being in other toolkits for about 9 months.</p>

<p>Thanks to the intrepid work of Sean Lynch at ( <a href="http://fairleads.blogspot.com/2007/12/rails-20-and-scaffolding-step-by-step.html">http://fairleads.blogspot.com/2007/12/rails-20-and-scaffolding-step-by-step.html</a> ) I found a tutorial that would familiarize me with the raw &#8220;how to scaffold&#8221; material.</p>

<p>I followed his tutorial&#8217;s step of:</p>

<p>&#8220;ruby script/generate scaffold Movie&#8221;</p>

<p>Great! From that point I filled in the &#8220;columns&#8221; in the migration as I had done in Rails 1.x.  All I should need to do is run &#8220;rake db:migrate&#8221; and try adding a new record via the dynamically-created view.</p>

<p>When I started the server and navigated localhost:3000/movies I had the &#8220;create new&#8221; button.  When I pushed that button there were no text widgets to enter <em>despite having defined the columns that corresponded to said widgets</em> having been added to the migration ( I have a lengthy blog post about how my diagnostics went, for anyone <a href="http://stevengharms.net/?p=1063">else&#8217;s edification</a> ).  In short the scaffold that had been created knew nothing of the columns I had added in the migration and, as such, the &#8216;new&#8217; view had no widgets.</p>

<p>This struck me as well, wrong.  On Sean&#8217;s post another user confirms the same experience.  I have tried it with sqlite3 / mysql / postgres connectors.</p>

<p>Research showed that the scaffold had remained static relative to the time that I had done the original aenemic invocation.  Per &#8220;script/generate scaffold &#8212;help&#8221;:</p>

<p>./script/generate scaffold post` # no attributes, view will be anemic</p>

<p>To fix this I had to re-issue the script/generate command with all the attributes in &#8220;final draft&#8221; mode ( &#8220;script/generate scaffold movie title:string text:description one_sheet_url:string&#8221; ) and then over-write the old templates ( output stored below, for legibility, Fig. 1).</p>

<p>The solution implies:</p>

<ul>
<li>You have to get the script/generate command&#8217;s &#8220;attributes&#8221; arguments <em>perfect</em> at time of creation OR </li>
<li>You do this overwriting thing that I describe below.  </li>
</ul>

<p>As I recall Rails 1.x&#8217;s dynamic scaffolding allowed us to use a scaffold flexibly strictly based on migrations and rake db:migrate.  This flexibility allowed us to &#8220;sketch&#8221; ideas very rapidly.  Or is it considered a &#8220;Good Thing&#8221; that you get a &#8220;perfected&#8221; &#8220;generate scaffold&#8221; command at some point?  If so, what&#8217;s the reasoning?  Am I missing some sort of rake command that &#8220;refreshes&#8221; the scaffold templates?</p>

<p>Based on the comments at Sean&#8217;s site and some of the questions in the comments to DHH&#8217;s Rails 2. announcement I think there are others grappling with this quandry as well.  Can anyone help?</p>

<p>Steven</p>

<p><span id="more-1065"></span></p>

<h2>Fig. 1</h2>

<pre>
bash-3.2$ script/generate scaffold movie title:string text:description one_sheet_url:string
      exists  app/models/
      exists  app/controllers/
      exists  app/helpers/
      exists  app/views/movies
      exists  app/views/layouts/
      exists  test/functional/
      exists  test/unit/
overwrite app/views/movies/index.html.erb? (enter "h" for help) [Ynaqdh] y
       force  app/views/movies/index.html.erb
overwrite app/views/movies/show.html.erb? (enter "h" for help) [Ynaqdh] y
       force  app/views/movies/show.html.erb
overwrite app/views/movies/new.html.erb? (enter "h" for help) [Ynaqdh] y
       force  app/views/movies/new.html.erb
overwrite app/views/movies/edit.html.erb? (enter "h" for help) [Ynaqdh] y
       force  app/views/movies/edit.html.erb
   identical  app/views/layouts/movies.html.erb
   identical  public/stylesheets/scaffold.css
  dependency  model
      exists    app/models/
      exists    test/unit/
      exists    test/fixtures/
   identical    app/models/movie.rb
   identical    test/unit/movie_test.rb
        skip    test/fixtures/movies.yml
      exists    db/migrate
Another migration is already named create_movies: db/migrate/001_create_movies.rb
</pre>
]]></content:encoded>
			<wfw:commentRss>http://stevengharms.com/scaffolding-has-changed-in-rails-20-has-it-become-un-agile/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

