<?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; activerecord</title>
	<atom:link href="http://www.jtanium.com/tag/activerecord/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>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>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>
		<item>
		<title>Handling Currency in Rails</title>
		<link>http://www.jtanium.com/2009/10/17/handling-currency-in-rails/</link>
		<comments>http://www.jtanium.com/2009/10/17/handling-currency-in-rails/#comments</comments>
		<pubDate>Sat, 17 Oct 2009 21:44:34 +0000</pubDate>
		<dc:creator>jtanium</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[currency]]></category>
		<category><![CDATA[currency_magic]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://www.jtanium.com/?p=158</guid>
		<description><![CDATA[So I recently ran into a situation where I had to start actually working with dollar amounts. I think that was pretty obvious given my last post about formatting currency in JavaScript. With the UI figured out, I was trying to deal with getting the amounts into the server. We all (hopefully) know you should [...]]]></description>
			<content:encoded><![CDATA[<p>So I recently ran into a situation where I had to start actually working with dollar amounts. I think that was pretty obvious given my last post about <a href="http://www.jtanium.com/2009/10/14/format-currency-in-javascript/">formatting currency in JavaScript</a>. With the UI figured out, I was trying to deal with getting the amounts into the server.</p>
<p>We all (hopefully) know you should always use integers to do your currency calculations.  But users like to have dollars and cents to work with. Somewhere is going to live some code that handles that conversion. One post I found gave the following solution: add a before_filter to go through and convert anything that looked like it might be a currency amount:</p>
<pre>
def filter_units (input)
 if [Array, Hash, HashWithIndifferentAccess].include?(input.class)
  input.each do |key, value|
   #recurse through the data structure
   input[key] = self.filter_units(value)
  end
 #match the string format for a major unit
 elsif not input.nil? and input.match(/^\d+\.\d\d)$/)
  #convert to a minor unit integer
  (input.to_f * 100.0).to_i
 else
  #return the value unchanged
  input
 end
end
</pre>
<p>No offense John, but that is a terrible way of dealing with it.  #1. I couldn&#8217;t even get the code to work, it gave all kinds of errors.  #2. What if you have another field the contains a float, e.g. tax_percent or weight_in_lbs, which aren&#8217;t currency, but could match the format above? #3. What about when a user decides to put in 9.5 instead of 9.50, or include a dollar sign themselves ($9.50)?  Finally, this still leaves you having to deal the conversion to a float by hand when it comes time to display the amount.</p>
<p>Here was my solution.  I just added some virtual attributes to my models:</p>
<pre>
class Subscription < ActiveRecord::Base
  def price_dollars
    (self.price / 100).round
  end
  def price_dollars=(price)
    self.price = (price.to_f * 100).to_i
  end
end
</pre>
<p>*Poof!* No cumbersome code!  But the above quickly becomes painful when you have several attributes, especially when they're spread across models.  So extracted the above into a plugin, which I, with a complete lack of creativity, named <a href="http://github.com/jtanium/currency_magic">CurrencyMagic</a>.</p>
<pre>
class Subscription < ActiveRecord::Base
  currency_magic :dollars, :price, :cost, :sales_price, :etc
end
</pre>
<p>Now, I'm not in love with the plugin idea, but I wanted to have a way to test the code and share it across projects, so that's what I did. I originally made it a module that could be included, so there's really nothing more than re-organizing the code for it to work outside ActiveRecord, though I imagine that would diminish it's value somewhat.</p>
<p>Anywho, there you go, my solution to converting dollars to cents and back in Rails.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtanium.com/2009/10/17/handling-currency-in-rails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

