<?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>Jtanium's Notebook &#187; Rails</title>
	<atom:link href="http://www.jtanium.com/category/rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jtanium.com</link>
	<description>I jot things down, in hopes of finding them later...</description>
	<lastBuildDate>Wed, 21 Dec 2011 23:21:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Service-Oriented Design with Ruby and Rails</title>
		<link>http://www.jtanium.com/2010/11/29/service-oriented-design-with-ruby-and-rails/</link>
		<comments>http://www.jtanium.com/2010/11/29/service-oriented-design-with-ruby-and-rails/#comments</comments>
		<pubDate>Mon, 29 Nov 2010 21:08:35 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=226</guid>
		<description><![CDATA[I got a copy of this book recently because I want to explore using web services more in some of my projects. If you are going to work through the examples, just be warned, they aren&#8217;t going to work out of the box. I don&#8217;t know who was supposed to be checking they work, but [...]]]></description>
			<content:encoded><![CDATA[<p>I got a copy of this book recently because I want to explore using web services more in some of my projects.</p>
<p>If you are going to work through the examples, just be warned, they aren&#8217;t going to work out of the box.  I don&#8217;t know who was supposed to be checking they work, but they dropped the ball.</p>
<p>This is where I&#8217;m going to keep track of all the things I had to change/tweak/massage to get it to work.</p>
<p><strong>Chapter 1: Implementing and Consuming Your First Service</strong></p>
<ul>
<li>You also need Rack-Test <code>gem install rack-test</code></li>
<li>The <code>Rackfile</code> and <code>spec/service_spec.rb</code> won&#8217;t work. I have created a <a href="https://gist.github.com/720605">gist</a> where you can view my comments about what I had to add.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2010/11/29/service-oriented-design-with-ruby-and-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apache, WordPress, Passenger, and You</title>
		<link>http://www.jtanium.com/2010/11/06/apache-wordpress-passenger-and-you/</link>
		<comments>http://www.jtanium.com/2010/11/06/apache-wordpress-passenger-and-you/#comments</comments>
		<pubDate>Sat, 06 Nov 2010 21:28:45 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Tips and Tricks]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=222</guid>
		<description><![CDATA[I was trying to get a web application running here along side WordPress, but, in essence, Apache wasn&#8217;t letting mod_rails handle the request. Several Google searches turned up precisely zero answers. After poking around I found the .htaccess file that WordPress so kindly generates for you: # BEGIN WordPress &#60;IfModule mod_rewrite.c&#62; RewriteEngine On RewriteBase / [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to get a web application running here along side WordPress, but, in essence, Apache wasn&#8217;t letting mod_rails handle the request.</p>
<p>Several Google searches turned up precisely zero answers.  After poking around I found the .htaccess file that WordPress so kindly generates for you:</p>
<pre># BEGIN WordPress
&lt;IfModule mod_rewrite.c&gt;
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
&lt;/IfModule&gt;

# END WordPress
</pre>
<p>What this little guy is doing is displaying a nice pretty 404 page, instead of a plain old ugly Apache page.  It does this by looking to see if there is a file or directory matching the file name in the request.</p>
<p>Obviously, there aren&#8217;t files and directories to correspond with your web app urls.  The solution is, quite simply, to tell Apache not to go looking for files and directories when the request needs to go to your web application.  So how do you that? Like this:</p>
<pre>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/myrailsapp.*
RewriteRule . /index.php [L]
</pre>
<p>Voila!  Now Apache won&#8217;t try looking for any files or directories when the request begins with &#8220;myrailsapp.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2010/11/06/apache-wordpress-passenger-and-you/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Queue Wait Spikes with Passenger and NewRelic</title>
		<link>http://www.jtanium.com/2010/05/17/queue-wait-spikes-with-passenger-and-newrelic/</link>
		<comments>http://www.jtanium.com/2010/05/17/queue-wait-spikes-with-passenger-and-newrelic/#comments</comments>
		<pubDate>Mon, 17 May 2010 21:07:42 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[newrelic]]></category>
		<category><![CDATA[passenger]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=206</guid>
		<description><![CDATA[So I&#8217;ve been struggling with &#8220;Queue Wait&#8221; spikes on NewRelic. I think I have pretty much determined that the spikes are caused by Passenger spinning up new threads to handle additional requests. Here&#8217;s what I did. First I restarted my app, and let it run for a bit, then I used &#8220;passenger-status&#8221; to see what [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been struggling with &#8220;Queue Wait&#8221; spikes on NewRelic.  I think I have pretty much determined that the spikes are caused by Passenger spinning up new threads to handle additional requests.  Here&#8217;s what I did.</p>
<p>First I restarted my app, and let it run for a bit, then I used &#8220;passenger-status&#8221; to see what the threads were doing:</p>
<pre>
----------- General information -----------
max      = 30
count    = 3
active   = 0
inactive = 3
Waiting on global queue: 0

----------- Domains -----------
/srv/rails/myapp/current:
  PID: 9734    Sessions: 0    Processed: 48      Uptime: 18m 54s
  PID: 9704    Sessions: 0    Processed: 49      Uptime: 19m 5s
  PID: 9706    Sessions: 0    Processed: 57      Uptime: 19m 2s
</pre>
<p>I&#8217;d basically just run it again every few minutes to see what was happening, and then I got this:</p>
<pre>

----------- General information -----------
max      = 30
count    = 4
active   = 0
inactive = 4
Waiting on global queue: 0

----------- Domains -----------
/srv/rails/myapp/current:
  PID: 9822    Sessions: 0    Processed: 34      Uptime: 4m 57s
  PID: 9706    Sessions: 0    Processed: 103     Uptime: 26m 43s
  PID: 9704    Sessions: 0    Processed: 107     Uptime: 26m 46s
  PID: 9734    Sessions: 0    Processed: 75      Uptime: 26m 35s

Mon May 17 13:54:20 MDT 2010
</pre>
<p>(I actually started running <code>passenger-status; date</code> so I could have the time I ran the command).  The above tells us that at roughly 13:49 Passenger spun up another thread.  Refreshing NewRelic, I saw this:</p>
<p><a href="https://www.jtanium.com/wp-content/uploads/2010/05/newrelic-queue_wait.png"><img src="https://www.jtanium.com/wp-content/uploads/2010/05/newrelic-queue_wait.png" alt="" title="newrelic-queue_wait" width="664" height="306" class="alignnone size-full wp-image-207" /></a></p>
<p>I spent more time investigating, and it does seem that the queue wait spikes, roughly correspond to times that Passenger starts more threads.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2010/05/17/queue-wait-spikes-with-passenger-and-newrelic/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Complex Associations in Factory Girl</title>
		<link>http://www.jtanium.com/2010/05/17/complex-associations-in-factory-girl/</link>
		<comments>http://www.jtanium.com/2010/05/17/complex-associations-in-factory-girl/#comments</comments>
		<pubDate>Mon, 17 May 2010 20:49:40 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[associations]]></category>
		<category><![CDATA[factory_girl]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=202</guid>
		<description><![CDATA[I finally decided to bite the bullet and move the main Rails project I work on from FixtureReplacement to Factory Girl. Weighing in at 7404 lines of test code, this was a non-trivial task. If you peruse the Factory Girl docs, it mentions associations, but only how to handle a simple &#8220;belongs to&#8221; or maybe [...]]]></description>
			<content:encoded><![CDATA[<p>I finally decided to bite the bullet and move the main Rails project I work on from <a href="http://replacefixtures.rubyforge.org/">FixtureReplacement</a> to <a href="http://github.com/thoughtbot/factory_girl">Factory Girl</a>.  Weighing in at 7404 lines of test code, this was a non-trivial task.</p>
<p>If you peruse the Factory Girl docs, it mentions associations, but only how to handle a simple &#8220;belongs to&#8221; or maybe &#8220;has one&#8221; sort of association.  My <a href="http://www.google.com">good friend</a> led me to <a href="http://stackoverflow.com/questions/1506556/has-many-while-respecting-build-strategy-in-factory-girl">this thread</a> on StackOverflow.</p>
<p>Basically, the user fowlduck came up with the solution of having an &#8220;after_build&#8221; block.</p>
<p>My problem couldn&#8217;t be solved with a simple &#8220;has_many/belongs_to&#8221; association, because in this case I needed to ensure the invoice seller matched the producer of the product being invoiced.  Here was my solution:</p>
<pre>
Factory.define :invoice do |i|
  i.after_build do |invoice|
    invoice.buyer = Factory.create :consumer unless invoice.buyer
    next if invoice.seller
    invoice.line_items = [Factory.create(:line_item)]
    invoice.seller = invoice.line_items.first.product.producer
  end
end
</pre>
<p>So first, notice the &#8220;unless invoice.buyer&#8221; and &#8220;next if invoice.seller&#8221; these allow me to override these values in my tests.  You&#8217;re gonna wanna keep that in mind. Next, I create a LineItem, which automatically creates a product, which in turn, creates a producer.  After that I can just set the seller to be the producer of the product in the first line item.  Voila, product line_item producer matches invoice seller.</p>
<p>I&#8217;ve found this tremendously useful.  Here&#8217;s another example of how I&#8217;ve used it:</p>
<pre>
Factory.define :user do |a|
  name = Faker::Name.name
  a.real_name { name }
  a.username { Faker::Internet.user_name(name) }
  a.password 'secret-1'
  a.password_confirmation 'secret-1'
  a.email_address { Faker::Internet.email(name) }
  a.after_build do |login|
    next if login.valid?
    next unless login.errors.invalid?(:username)
    login.username = Faker::Internet.user_name(login.real_name)+String.random(4)
  end
end
</pre>
<p>I did this because, everyone once in a great while my tests would fail because the same username is used more than once.  But now, if this happens, I just tack on 4 random characters.  Since i did this, I haven&#8217;t had the test fail.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2010/05/17/complex-associations-in-factory-girl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Capistrano + Fetcher/Daemonize</title>
		<link>http://www.jtanium.com/2010/03/12/capistrano-fetcher-daemonize/</link>
		<comments>http://www.jtanium.com/2010/03/12/capistrano-fetcher-daemonize/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 21:51:17 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[capistrano]]></category>
		<category><![CDATA[fetcher]]></category>
		<category><![CDATA[nohup]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[task]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=200</guid>
		<description><![CDATA[So I&#8217;ve spent the afternoon slogging through this little problem. Something tells me I&#8217;m going to be referring to this post again and again. Are you using the fetcher plugin and Capistrano for deployment? Hey, me too! Apparently I&#8217;m the only one in the world who didn&#8217;t immediately know how to make them work together [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve spent the afternoon slogging through this little problem.  Something tells me I&#8217;m going to be referring to this post again and again.</p>
<p>Are you using the <a href="http://github.com/look/fetcher">fetcher plugin</a> and <a href="http://www.capify.org">Capistrano</a> for deployment? Hey, me too! Apparently I&#8217;m the only one in the world who didn&#8217;t immediately know how to make them work together though.</p>
<p>Here are my Capistrano tasks for starting/stopping/restarting my fetcher daemons:</p>
<pre>
after "deploy:restart", "fetcher:restart"

namespace :fetcher do
  desc "Stop the fetcher_mailer daemons"
  task :stop, :roles => :app do
    run "RAILS_ENV=#{rails_env} ruby #{current_path}/script/mailer_daemon_fetcher stop"
  end

  desc "Start the fetcher_mailer daemons"
  task :start, :roles => :app do
    run "RAILS_ENV=#{rails_env} nohup /opt/ruby-enterprise/bin/ruby #{current_path}/script/mailer_daemon_fetcher start", :pty => true
  end

  desc "Restart (cycle) the fetcher_mailer daemons"
  task :restart, :roles => :app do
    stop
    start
  end
end
</pre>
<p>The real key here is on the <code>:start</code> task, there are two things you need to do to get the shell to let go of the process.:</p>
<ol>
<li>Add the <a href="http://en.wikipedia.org/wiki/Nohup"><code>nohup</code></a> to your command.  If you don&#8217;t do this the process goes into the background, and as soon as the shell exits the OS says &#8220;SIGHUP&#8221; (&#8220;you don&#8217;t have to go home, but you can&#8217;t stay here.&#8221;)</li>
<li>The second thing is the <code>:pty => true</code>.  This tells Capistrano to request a <a href="http://en.wikipedia.org/wiki/Pseudo_terminal">pseudo terminal</a>. I don&#8217;t know all the nitty gritty, and have neither the time nor the inclination to dig in and find out why.</li>
</ol>
<p>So there you go, add a <code>nohup</code> and <code>:pty => true</code> and then you can get your fetcher daemon backgrounded.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2010/03/12/capistrano-fetcher-daemonize/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ActionView::TestCase and nil.url_for</title>
		<link>http://www.jtanium.com/2010/02/16/actionviewtestcase-and-nil-url_for/</link>
		<comments>http://www.jtanium.com/2010/02/16/actionviewtestcase-and-nil-url_for/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 18:25:26 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=198</guid>
		<description><![CDATA[If you&#8217;re having problems testing your helpers because of messages like these: The error occurred while evaluating nil.url_for The problem, it turns out is ActionView::TestCase doesn&#8217;t like url_for, it seems to expect you&#8217;re using named routes. So, in your helper, instead of doing something like: def link_to_awesomeness(my_object) if my_object.awesome? link_to 'Awesomeness', :action => 'show_awesomeness', :id [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re having problems testing your helpers because of messages like these:</p>
<pre>The error occurred while evaluating nil.url_for
</pre>
<p>The problem, it turns out is ActionView::TestCase doesn&#8217;t like <code>url_for</code>, it seems to expect you&#8217;re using named routes.  So, in your helper, instead of doing something like:</p>
<pre>
def link_to_awesomeness(my_object)
  if my_object.awesome?
    link_to 'Awesomeness', :action => 'show_awesomeness', :id => my_object
  else
    link_to 'Make Awesome', :action => 'make_awesome', :id => my_object
  end
end
</pre>
<p>Try something more like this:</p>
<pre>
def link_to_awesomeness(my_object)
  if my_object.awesome?
    link_to 'Awesomeness', awesomeness_path(my_object)
  else
    link_to 'Make Awesome', make_awesome_path(my_object)
  end
end
</pre>
<p>Of course this implies you&#8217;ve created those named routes in your <code>config/routes.rb</code>, e.g.:</p>
<pre>
map.awesomeness 'my_objects/:id/awesomeness', :controller => 'my_objects', :action => 'show_awesomeness'
map.make_awesome 'my_objects/:id/make_awesome', :controller => 'my_objects', :action => 'make_awesome'
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2010/02/16/actionviewtestcase-and-nil-url_for/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun Little ActiveRecord Gotcha</title>
		<link>http://www.jtanium.com/2009/12/17/fun-little-activerecord-gotcha/</link>
		<comments>http://www.jtanium.com/2009/12/17/fun-little-activerecord-gotcha/#comments</comments>
		<pubDate>Thu, 17 Dec 2009 19:47:00 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=192</guid>
		<description><![CDATA[So I was cruising along adding a new model to a project. The model is being used to store credit card information and when I generated the model, I absentmindedly did: script/generate model CreditCard ... encrypted_expiration_date:date ... Chugging along writing my tests I wrote a test like this: class CreditCardTest < ActiveSupport::TestCase context "A CreditCard [...]]]></description>
			<content:encoded><![CDATA[<p>So I was cruising along adding a new model to a project.  The model is being used to store credit card information and when I generated the model, I absentmindedly did:</p>
<pre>
script/generate model CreditCard ... encrypted_expiration_date:date ...
</pre>
<p>Chugging along writing my tests I wrote a test like this:</p>
<pre>
class CreditCardTest  < ActiveSupport::TestCase
  context "A CreditCard instance" do
    subject { CreditCard.new(:expiration_date => new_expiration_date) }
    should("ensure expiration_date is encrypted") do
      assert_equal expiration_date_cipher_text, subject.encrypted_expiration_date
    end
    def new_expiration_date; Date.today+90; end
    def expiration_date_cipher_text; "!!!EXPIRATION_DATE_CIPHER_TEXT!!!"; end
  end
</pre>
<p>And the model looking something like this:</p>
<pre>
class CreditCard < ActiveRecord::Base
  def expiration_date=(exp_date)
    @expiration_date = exp_date
    self.encrypted_expiration_date = encrypt(exp_date)
end
</pre>
<p>The test would fail every time like:</p>
<pre>
Finished in 0.030941 seconds.

  1) Failure:
test:  should encrypt expiration_date. (CreditCardTest)
    [test/unit/credit_card_test.rb:53:in `__bind_1261076018_868915'
     shoulda (2.10.2) [v] lib/shoulda/context.rb:351:in `call'
     shoulda (2.10.2) [v] lib/shoulda/context.rb:351:in `test:  should encrypt expiration_date. ']:
<"!!!EXPIRATION_DATE_CIPHER_TEXT!!!"> expected but was
<nil>.

1 tests, 1 assertions, 1 failures, 0 errors
</pre>
<p>Can you guess the problem?  Ten points to Gryffindor if you said it's because the column type is date.  And another five points if you can say it's because ActiveRecord is tries to parse it to be a date object, which fails, and returns nil.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2009/12/17/fun-little-activerecord-gotcha/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Expected response to be a &lt;:redirect&gt;, but was &lt;0&gt;</title>
		<link>http://www.jtanium.com/2009/11/20/expected-response-to-be-a-redirect-but-was-0/</link>
		<comments>http://www.jtanium.com/2009/11/20/expected-response-to-be-a-redirect-but-was-0/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 22:34:58 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/2009/11/20/expected-response-to-be-a-but-was/</guid>
		<description><![CDATA[If you&#8217;re seeing this in your test: Expected response to be a &#60;:redirect&#62; , but was &#60;0&#62; You are probably doing something like this in your controller: redirect_to :action => 'messages', :status => 'read' Watch out when using :status in your params. :status is used to set the http status code in the redirect_to method, [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re seeing this in your test:</p>
<pre>Expected response to be a &lt;:redirect&gt; , but was &lt;0&gt;</pre>
<p>You are probably doing something like this in your controller:</p>
<pre>redirect_to :action => 'messages', :status => 'read'
</pre>
<p>Watch out when using <code>:status</code> in your params.  <code>:status</code> is used to set the http status code in the <code>redirect_to</code> method, like so:</p>
<pre>redirect_to :action=>'atom', :status=>302
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2009/11/20/expected-response-to-be-a-redirect-but-was-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rails fields_for &#8220;is not allowed as an instance variable name&#8221;</title>
		<link>http://www.jtanium.com/2009/11/03/rails-fields_for-is-not-allowed-as-an-instance-variable-name/</link>
		<comments>http://www.jtanium.com/2009/11/03/rails-fields_for-is-not-allowed-as-an-instance-variable-name/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 21:22:34 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=173</guid>
		<description><![CDATA[So I&#8217;ve been trying to figure this error out, it just cropped up: `@my_object[such_and_such_attributes]' is not allowed as an instance variable name As is usually the case with Rails, the answer is pretty obvious once you understand what&#8217;s going on. Here&#8217;s the relevant code: &#60;% fields_for 'my_object[such_and_suches_attributes]', @my_object.such_and_suches.first do &#124;such_and_such_form&#124; -%&#62; &#60;%= such_and_such_form.text_field :name %&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been trying to figure this error out, it just cropped up:</p>
<pre>
`@my_object[such_and_such_attributes]' is not allowed as an instance variable name
</pre>
<p>As is usually the case with Rails, the answer is pretty obvious once you understand what&#8217;s going on. Here&#8217;s the relevant code:</p>
<pre>
&lt;% fields_for 'my_object[such_and_suches_attributes]', @my_object.such_and_suches.first do |such_and_such_form| -%&gt;
  &lt;%= such_and_such_form.text_field :name %&gt;
&lt;% end -%&gt;
</pre>
<p>So why was the above creating the error? It&#8217;s because @my_object.such_and_suches was empty, thus Rails would try and use &#8220;my_object[such_and_suches_attributes]&#8221; as the attribute name which naturally didn&#8217;t work.  This is the shortcut that allows this to work:</p>
<pre>
&lt;% fields_for :posts do |post_form| -%&gt;
  &lt;%= post_form.text_field :title %&gt;
&lt;% end -%&gt;
</pre>
<p>Now in my situation, why the &#8220;such_and_suches&#8221; is empty is a whole other problem&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2009/11/03/rails-fields_for-is-not-allowed-as-an-instance-variable-name/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails/ActiveRecord: belongs_to :polymorphic =&gt; true</title>
		<link>http://www.jtanium.com/2009/10/22/railsactiverecord-belongs_to-polymorphic-true/</link>
		<comments>http://www.jtanium.com/2009/10/22/railsactiverecord-belongs_to-polymorphic-true/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 20:05:55 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[belongs_to]]></category>
		<category><![CDATA[has_many]]></category>
		<category><![CDATA[polymorphic]]></category>
		<category><![CDATA[polymorphism]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=161</guid>
		<description><![CDATA[This morning, I was looking for a way to have an ActiveRecord object &#8220;belong to&#8221; one of a handful of different object types. That&#8217;s when I came across the :polymorphic option of the belongs_to method. From the description and the &#8220;Polymorphic&#8221; section of the docs it seemed like it would do what I need, so [...]]]></description>
			<content:encoded><![CDATA[<p>This morning, I was looking for a way to have an ActiveRecord object &#8220;belong to&#8221; one of a handful of different object types.  That&#8217;s when I came across the <code>:polymorphic</code> option of the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001835"><code>belongs_to</code></a> method.</p>
<p>From the description and the &#8220;Polymorphic&#8221; section of the docs it seemed like it would do what I need, so I set out to figure out how to use it.  I was looking for an easy clear description of how it&#8217;s used, but several Google searches produced nothing. So I decided to make one myself.</p>
<p>We&#8217;ll start off with a little project used to track items in a &#8220;media library,&#8221; e.g. Books, Music, and Movies. Given the following models:</p>
<pre>
script/generate model Book author:string title:string summary:string isbn:string
script/generate model Album artist:string title:string track_listing:string
script/generate model Movie director:string title:string summary:string
script/generate model Artwork library_item_id:integer library_item_type:string
</pre>
<p>We want our Book, Album, and Movie objects to have one or more &#8220;Artwork&#8221; objects to represent covers or movie posters. First let&#8217;s tell the Artwork class it belongs to the other objects:</p>
<pre>class Artwork < ActiveRecord::Base
  belongs_to :library_item, :polymorphic => true
end
</pre>
<p>Notice how the <code>:library_item</code> corresponds to the columns we defined: <code>library_item_id</code> and <code>library_item_type</code>. ActiveRecord is going to store the <code>Book#id</code>, <code>Album#id</code>, or <code>Movie#id</code> in the <code>library_item_id</code>. In the <code>library_item_type</code> column ActiveRecord will put <code>"Book"</code>, <code>"Album"</code>, or <code>"Movie"</code>, as appropriate.  For example, if you do this:</p>
<pre>
&gt;&gt; Artwork.new(:library_item =&gt; Book.create)
=&gt; #&lt;Artwork id: nil, library_item_id: 1, library_item_type: "Book", created_at: nil, updated_at: nil&gt;
</pre>
<p>The <code>library_item_id</code> and <code>library_item_type</code> columns will have <code>Book#id</code>, in this case &#8217;1&#8242;, and <code>Book#class</code>, which is <code>Book</code>, respectively.</p>
<p>Now here&#8217;s how the <code>Book</code>, <code>Album</code>, and <code>Movie</code> classes are tied to the &#8220;artwork&#8221;:</p>
<pre>
class Book < ActiveRecord::Base
  has_one :cover_image, :class_name => 'Artwork', :as => :library_item
end
class Album < ActiveRecord::Base
  has_one :cover_art, :class_name => 'Artwork', :as => :library_item
end
class Movie < ActiveRecord::Base
  has_one :poster_image, :class_name => 'Artwork', :as => :library_item
end
</pre>
<p>This gives us methods like <code>Album#cover_art</code> we can use to reference the Artwork object from the Album object.</p>
<p>So there you go, hopefully this proves useful&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2009/10/22/railsactiverecord-belongs_to-polymorphic-true/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

