<?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>Ontic Oren &#187; Code</title>
	<atom:link href="http://onticoren.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://onticoren.com</link>
	<description>Enough virtual, it's time for something real by Oren Teich.</description>
	<lastBuildDate>Thu, 14 Jan 2010 23:55:38 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Direct SQL queries in Rails apps</title>
		<link>http://onticoren.com/2009/12/17/direct-sql-queries-in-rails-apps/</link>
		<comments>http://onticoren.com/2009/12/17/direct-sql-queries-in-rails-apps/#comments</comments>
		<pubDate>Thu, 17 Dec 2009 17:25:38 +0000</pubDate>
		<dc:creator>teich</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://onticoren.com/?p=160</guid>
		<description><![CDATA[I&#8217;ve been working on some stats tracking.  This means a lot of complex queries, and sometimes ActiveRecord just doesn&#8217;t cut it.  Doing it the ruby way (or at least, the ruby way I know how to do) would often mean queries &#62; 30 seconds.  A simple SQL query could get me the same data in [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working on some stats tracking.  This means a lot of complex queries, and sometimes ActiveRecord just doesn&#8217;t cut it.  Doing it the ruby way (or at least, the ruby way I know how to do) would often mean queries &gt; 30 seconds.  A simple SQL query could get me the same data in &lt;100ms.  For some reason, I was having a really hard time figuring out how to do direct SQL queries though.  After banging my head, here&#8217;s what I figured out.</p>
<p>There are two ways to directly query the DB with AR: find_by_sql and ActiveRecord::Base.connection.execute.  They each have their place, and I use both.</p>
<p><strong>find_by_sql</strong><br />
find_by_sql is super easy, as it actually returns an ActiveRecord object.  This means you don&#8217;t need to do anything unusual.  It works on an object, and works great when you&#8217;re selecting fields from that object specifically.  Here&#8217;s an example of how I use find_by_sql and some fun SQL to get a funnel of our users:</p>
<pre class="brush: ruby;">
@funnel = User.find_by_sql(&quot;SELECT DATE_TRUNC('month', created_at) AS month,
             COUNT(id) AS registered,
             SUM(CASE WHEN verified_at IS NOT NULL THEN 1 ELSE 0 END) AS verified,
             SUM(CASE WHEN confirmed_billing_at IS NOT NULL THEN 1 ELSE 0 END) as confirmed
FROM users
GROUP BY DATE_TRUNC('month', created_at)
ORDER BY month&quot;)
</pre>
<p><strong>connection.execute</strong><br />
The other way to execute SQL is with connection.execute.  This returns a database specific object, for example a PGrecord for my postgres database.  You can then iterate over that object like any standard ruby array of hashes.  The hash key will be the SQL header.  Here&#8217;s an example where I calculate the # of new user signups per week:</p>
<pre class="brush: ruby;">
sql = &quot;SELECT COUNT(*), DATE_TRUNC('week', created_at) FROM USERS GROUP BY DATE_TRUNC('week', created_at)&quot;
results = ActiveRecord::Base.connection.execute(sql)
results.each do |foo|
  puts &quot;#{foo['date_trunc']} #{foo['count']}&quot;
end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://onticoren.com/2009/12/17/direct-sql-queries-in-rails-apps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keep an eye on your ordered assumptions</title>
		<link>http://onticoren.com/2009/05/31/keep-an-eye-on-your-ordered-assumptions/</link>
		<comments>http://onticoren.com/2009/05/31/keep-an-eye-on-your-ordered-assumptions/#comments</comments>
		<pubDate>Sun, 31 May 2009 19:34:42 +0000</pubDate>
		<dc:creator>teich</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[rubyonrails]]></category>

		<guid isPermaLink="false">http://onticoren.com/?p=128</guid>
		<description><![CDATA[A nasty bug on ZED9 I&#8217;ve been avoiding the past few days was solved with a stupid single line.
In Rails, when you have a has_many relationship, it&#8217;s great and easy to be able to iterate through all the items.  Assume you have models as such

class Foo &#60; ActiveRecord::Base
    has_many :bars
end

class Bar [...]]]></description>
			<content:encoded><![CDATA[<p>A nasty bug on ZED9 I&#8217;ve been avoiding the past few days was solved with a stupid single line.</p>
<p>In Rails, when you have a has_many relationship, it&#8217;s great and easy to be able to iterate through all the items.  Assume you have models as such</p>
<pre class="brush: ruby;">
class Foo &lt; ActiveRecord::Base
    has_many :bars
end

class Bar &lt; ActiveRecord::Base
    belongs_to :foo
end
</pre>
<p>So you go ahead and iterate through them:</p>
<pre class="brush: ruby;">@foo = Foo.find(:last)
@foo.bars.each {|f| f.your.logic.here}
</pre>
<p>If  for anyreason, you&#8217;re counting on the ordering of those items, watch out!  I was iterating through GPS coordinates, comparing them with the first one.  SQL databases make no promise on ordering if you don&#8217;t ask for it, and every now and then I was getting totally insane results.  Turns out the DB was feeding me the GPS coordinates in reverse order sometimes.</p>
<p>Luckily, rails makes this very easy.  Just specify your ordering in the model:</p>
<pre class="brush: ruby;">
class Foo &lt; ActiveRecord::Base
    has_many :bars, :order =&gt; 'time ASC'
end
</pre>
<p>With that one line, I fixed half a dozen outstanding bugs.  Mostly posting so I&#8217;m not stupid in the future.</p>
]]></content:encoded>
			<wfw:commentRss>http://onticoren.com/2009/05/31/keep-an-eye-on-your-ordered-assumptions/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->