<?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>Jan Varwig &#187; rubyonrails</title>
	<atom:link href="http://jan.varwig.org/archive/tag/rubyonrails/feed" rel="self" type="application/rss+xml" />
	<link>http://jan.varwig.org</link>
	<description>Somewhere between Hello World and HAL9000</description>
	<lastBuildDate>Sat, 03 Dec 2011 00:15:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>REST in Place 2.0</title>
		<link>http://jan.varwig.org/archive/rest-in-place-2-0?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rest-in-place-2-0</link>
		<comments>http://jan.varwig.org/archive/rest-in-place-2-0#comments</comments>
		<pubDate>Sat, 03 Dec 2011 00:15:10 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[rest in place]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rubyonrails]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/?p=662</guid>
		<description><![CDATA[Two weeks ago I began rewriting REST in Place as a gemplugin for the Rails 3.1 asset pipeline. I just pushed the final version 2.0 to github and rubygems.org and want to give some hints on the new direction of the project. REST in Place has never been more than a proof-of-concept for me. It [...]]]></description>
			<content:encoded><![CDATA[<p>Two weeks ago I began rewriting REST in Place as a gemplugin for the Rails 3.1 asset pipeline.
I just pushed the final version 2.0 to github and rubygems.org and want to give some hints on the new direction of the project.</p>

<p>REST in Place has never been more than a proof-of-concept for me. It worked, pretty well even, so I never bothered much to develop it further, especially since integrating JavaScript code with Rails apps was a bit of a pain. I did only the barest, necessary maintenance and never actually realized that there are people out there using it.</p>

<p>When Rails 3.1 came out, there was finally a way to properly integrate the code into Rails, so I sat down on a weekend and made some massive changes to REST in Place:</p>

<ul>
<li><strong>No more standalone</strong><br />
Since I don&#8217;t think anyone is using it in a different way, REST in Place is
now a pure Rails 3.1 gemplugin using the asset pipeline</li>
<li><strong>Specs</strong><br />
To facilitate development of new features and refactoring, the app now has a
<a href="http://pivotal.github.com/jasmine/">Jasmine</a> spec suite in the testapp. It can be run by visiting
<code>http://localhost:3000/jasmine</code></li>
<li><strong>CoffeeScript</strong><br />
Because if you&#8217;re not using <a href="http://jashkenas.github.com/coffee-script/">CoffeScript</a> there&#8217;s something wrong with you. It
makes JavaScript bearable again.</li>
<li><strong>Proper CSRF token support</strong><br />
This was hacky in the past but for a while Rails includes a standard mechanism
for providing CSRF information to JavaScript running on the page.</li>
<li><strong>Automatic detection of <code>include_root_in_json</code> setting in Rails</strong><br />
Through the magic of erb and the asset pipeline, REST in Place can detect
how you&#8217;ve configured ActiveRecord.</li>
<li><strong>BC breaking interface changes</strong><br />
Two major things have changed that might trip you up:

<ul>
<li>The default css class for REST in Place is now <code>rest-in-place</code> and not 
<code>rest_in_place</code>.</li>
<li>Elements with that default class are initialized automatically on
<code>document.ready</code>.</li>
<li>The jQuery function to intialize elements with a REST in Place Editor was
renamed from <code>rest_in_place()</code> to <code>restInPlace()</code>.</li>
</ul></li>
</ul>

<p>All this is now available in a nice gem. All you need to do is add <code>gem 'rest_in_place'</code> to your Gemfile and you&#8217;re rollin&#8217; (You might want to take a look into the README first).</p>

<p>Now that I have CoffeeScript and specs, development of new features can be done much faster and easier.
Some things I have planned:</p>

<ul>
<li>Differentiate between manual abort and a failure</li>
<li>Validations/proper error responses</li>
<li>Maybe a nicer set of default widgets and UI improvements</li>
<li>Rails view helpers</li>
</ul>

<p>Especially the last two points go a bit against my original intentions for REST in Place, but if it helps more people to use it, hell, why not.</p>

<p>Unfortunately, these changes have come with a <em>very</em> bad timing. <em>One day</em> after I pushed the first beta of 2.0 to github, Ryan Bates did a <a href="http://railscasts.com/episodes/302-in-place-editing">Railscast about in place editing</a>. While REST in Place is mentioned there, he&#8217;s showing <a href="https://github.com/bernat/best_in_place">Best In Place</a>, a pretty extensive fork of my code that already has most of what I just wrote (asset pipeline, specs) or am going to write (validations, helpers).</p>

<p>Well, as frustrating as that was, I didn&#8217;t come as much of a surprise, considered how I&#8217;ve neglected REST in Place&#8217;s development in the past. I won&#8217;t repeat that mistake again, promise.</p>
 <p><a href="http://jan.varwig.org/?flattrss_redirect&amp;id=662&amp;md5=040ec4b10e7de4f54357a94226637c09" title="Flattr" target="_blank"><img src="http://jan.varwig.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/rest-in-place-2-0/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>REST in Place now with Multiline Editor</title>
		<link>http://jan.varwig.org/archive/rest-in-place-now-with-multiline-editor?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rest-in-place-now-with-multiline-editor</link>
		<comments>http://jan.varwig.org/archive/rest-in-place-now-with-multiline-editor#comments</comments>
		<pubDate>Fri, 05 Feb 2010 18:00:36 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[rest in place]]></category>
		<category><![CDATA[rubyonrails]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/?p=247</guid>
		<description><![CDATA[Yesterday I pushed the changes introducing the Multiline editor to REST in Place I announced last week. The definition of forms for editing inline-content is now separated from the Code that deals with Ajax and editing state. This makes it very easy to extend REST in Place with your own Editors. I also decided to [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I pushed the changes introducing the Multiline editor to REST in Place I announced last week.</p>

<p>The definition of forms for editing inline-content is now separated from the Code that deals with Ajax and editing state.
This makes it very easy to extend REST in Place with your own Editors.</p>

<p>I also decided to keep the jQuery backwards compatibility for a bit longer.</p>

<p>Check out the changes at <a href="http://github.com/janv/rest_in_place.git">http://github.com/janv/rest_in_place.git</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/rest-in-place-now-with-multiline-editor/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>REST in Place: Major update ahead</title>
		<link>http://jan.varwig.org/archive/rest-in-place-major-update-ahead?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rest-in-place-major-update-ahead</link>
		<comments>http://jan.varwig.org/archive/rest-in-place-major-update-ahead#comments</comments>
		<pubDate>Mon, 25 Jan 2010 00:08:44 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[inplace editor]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[rest in place]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rubyonrails]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/?p=237</guid>
		<description><![CDATA[This week, I&#8217;ll roll out a major update to REST in Place. I have completely restructured the code and made the Plugin much more object-oriented, modular and maintainable. Existing installations should be able to upgrade without a hitch. The most important change for users will be the jQuery 1.4 support and support for different editors [...]]]></description>
			<content:encoded><![CDATA[<p>This week, I&#8217;ll roll out a major update to <a href="http://github.com/janv/rest_in_place/">REST in Place</a>. I have completely restructured the code and made the Plugin much more object-oriented, modular and maintainable. Existing installations should be able to upgrade without a hitch. The most important change for users will be the jQuery 1.4 support and support for different editors (such as textarea, checkbox, etc.).</p>

<p>In November I got some pull requests for REST in Place which I didn&#8217;t get to really have a look at until last week. I haven&#8217;t really touched REST in Place in ages and wasn&#8217;t really aware that it was that popular. It has 72 followers and 11 forks on github and who knows how many other people are just silently using it! So, I merged in the contributions and dealt with some issues in the tracker and thought about how to go on.</p>

<p>REST in Place originally was a mere proof of concept and one of my first projects in JavaScript and jQuery. I have since written a lot more complicated applications and even a diploma thesis on JavaScript and the old code just isn&#8217;t up to my standards anymore. Additionally I have received several pull requests for textarea support which all couldn&#8217;t be merged because they were just copypasted and modified a little from the input-tag version. The only solution was a complete rewrite and that&#8217;s what I did. While the plugin still works the same way, the code is properly split up and more modular now. This enables easy extension and maintenance from now on and hopefully quicker development from me and better patches from all users.</p>

<p>This new development has some drawbacks too, unfortunately. This massive improvement will only go to the jQuery version of REST in Place. Since I don&#8217;t know much about Prototype or mootools, I can&#8217;t support both versions anymore. If someone is willing to work with me on this, I&#8217;ll happily accept their contributions but I can&#8217;t do this on my own. If anyone is willing to do so, please reply in the comments, so we can work out a plan. I want to keep all three versions as similar as possible, this means the Prototype and mootools versions should follow the same object-oriented structure as the jQuery version.</p>

<p>One last thing: I will support jQuery &lt; 1.4 until 1.4.1 comes out. 1.4 introduced some very nice changes which I&#8217;d like to make use of but since 1.4 seems a little buggy still, I&#8217;ll continue to support the older versions for a little while.</p>
]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/rest-in-place-major-update-ahead/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails Extremcrashkurs</title>
		<link>http://jan.varwig.org/archive/ruby-on-rails-extremcrashkurs?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ruby-on-rails-extremcrashkurs</link>
		<comments>http://jan.varwig.org/archive/ruby-on-rails-extremcrashkurs#comments</comments>
		<pubDate>Fri, 27 Mar 2009 01:05:56 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[crashkurs]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rubyonrails]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/?p=155</guid>
		<description><![CDATA[(Sorry, content in german only for this post) Ende 2007 habe ich bei 9elements einen Crashkurs zu Ruby on Rails gegeben. Da mich inzwischen schon mehrere Leute gefragt haben ob ich die Folien nicht mal rausgeben möchte, tue ich das jetzt. Die Folien sind absichtlich so gestaltet, dass sie auch ausserhalb des Vortrags als Nachschlagewerk [...]]]></description>
			<content:encoded><![CDATA[<p>(Sorry, content in german only for this post)</p>

<p>Ende 2007 habe ich bei <a href="http://www.9elements.com/">9elements</a> einen Crashkurs zu Ruby on Rails gegeben.
Da mich inzwischen schon mehrere Leute gefragt haben ob ich die Folien nicht mal rausgeben möchte, tue ich das jetzt.
Die Folien sind absichtlich so gestaltet, dass sie auch ausserhalb des Vortrags als Nachschlagewerk für Ruby dienen können.
Der Rails-Teil ist ein wenig arg knapp gehalten und kann vor allem einen groben Überblick in den Aufbau des Frameworks geben.</p>

<p><a href='http://jan.varwig.org/wp-content/uploads/2009/03/ruby-rails.pdf'>Ruby &amp; Rails Extremcrashkurs</a> (PDF-Link) v1.0 27.03.09</p>
]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/ruby-on-rails-extremcrashkurs/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting started with Ruby on Rails</title>
		<link>http://jan.varwig.org/archive/getting-started-with-ruby-on-rails?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-ruby-on-rails</link>
		<comments>http://jan.varwig.org/archive/getting-started-with-ruby-on-rails#comments</comments>
		<pubDate>Fri, 20 Mar 2009 10:43:23 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rubyonrails]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/?p=144</guid>
		<description><![CDATA[Today Smashing Magazine published an article I wrote last week about Ruby on Rails. Instead of just doing another tutorial, I gave a rough overview of how Rails works, together with a lot of praise of the language and the framework. I tried to spark interest in Rails and Ruby and judging from the first [...]]]></description>
			<content:encoded><![CDATA[<p>Today Smashing Magazine published an <a href="http://smashingmagazine.com/2009/03/19/getting-started-with-ruby-on-rails/">article I wrote last week about Ruby on Rails</a>.
Instead of just doing another tutorial, I gave a rough overview of how Rails works,
together with a lot of praise of the language and the framework.</p>

<p>I tried to spark interest in Rails and Ruby and judging from the first comments I think it worked :)</p>

<p>The text released today is only the first part, covering just enough Ruby to understand the second part coming out next week. If you like the article, please digg it or promote it on reddit/delicious/slashdot.</p>
]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/getting-started-with-ruby-on-rails/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>REST in Place now Rails 2.0 compatible</title>
		<link>http://jan.varwig.org/archive/rest-in-place-now-rails-20-compatible?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rest-in-place-now-rails-20-compatible</link>
		<comments>http://jan.varwig.org/archive/rest-in-place-now-rails-20-compatible#comments</comments>
		<pubDate>Fri, 27 Jun 2008 17:41:27 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[on Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[rest in place]]></category>
		<category><![CDATA[rubyonrails]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/?p=86</guid>
		<description><![CDATA[Ever since Rails 2.0 came out, my REST in Place Plugins stopped working because of the request forgery protecting introduced into ActiveController. The AJAX request didn&#8217;t submit the rails authenticity token and the requests weren&#8217;t answered. I fixed that problem yesterday in both the jQuery and the Prototype version (both included in the plugin.) Check [...]]]></description>
			<content:encoded><![CDATA[<p>Ever since Rails 2.0 came out, my REST in Place Plugins stopped working because of the request forgery protecting introduced into ActiveController. The AJAX request didn&#8217;t submit the rails authenticity token and the requests weren&#8217;t answered.</p>

<p>I fixed that problem yesterday in both the <a href="http://www.jquery.com/">jQuery</a> and the <a href="http://www.prototypejs.org/">Prototype</a> version (both included in the plugin.)</p>

<p>Check it out on the <a href="http://jan.varwig.org/projects/rest-in-place">REST in Place</a> project page.</p>
]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/rest-in-place-now-rails-20-compatible/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why bloggers suck</title>
		<link>http://jan.varwig.org/archive/why-bloggers-suck?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-bloggers-suck</link>
		<comments>http://jan.varwig.org/archive/why-bloggers-suck#comments</comments>
		<pubDate>Mon, 09 Jun 2008 19:10:04 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[blogging]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[rubyonrails]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/?p=84</guid>
		<description><![CDATA[Today a post by Reg Braithwaite brought to my attention several blogposts about ActiveRecords alledged shortcomings. Most of their writers are posting rants rants about some ideas they have about ActiveRecord without ever having really used it, it seems. The main issues seem to be Domain-code in your controllers instead of your models Rails choice [...]]]></description>
			<content:encoded><![CDATA[<p>Today a <a href="http://weblog.raganwald.com/2008/06/bitchiness-also-sucks.html">post by Reg Braithwaite</a> brought to my attention <a href="http://nothinghappens.net/?p=324">several</a> <a href="http://kore-nordmann.de/blog/why_active_record_sucks.html">blogposts</a> <a href="http://blog.mikeseth.com/index.php?/archives/4-ActiveRecord-sucks,-but-Kore-Nordmann-is-wrong.html">about ActiveRecords</a> <a href="http://karwin.blogspot.com/2008/05/activerecord-does-not-suck.html">alledged shortcomings</a>.
Most of their writers are posting rants rants about some ideas they have about ActiveRecord without ever having really used it, it seems. The main issues seem to be</p>

<ul>
<li>Domain-code in your controllers instead of your models</li>
<li>Rails choice of inheritance (AR as a base class for models)  for implementing AR</li>
</ul>

<p>Putting domain code inside your controllers is a programmer problem, not a framework problem.
I won&#8217;t even elaborate this any further.</p>

<p>The other issue is trickier. Not because of technical issues but because there&#8217;s a problem with the perception of Rails ActiveRecord. I first didn&#8217;t even want to waste my time to write this rant but then I started a comment on one of the postings that turned longer and longer until I decided to make a post of it.</p>

<p>Bill Karwin wrote some observations that I can mostly agree with.
There&#8217;s one exception though: I don&#8217;t see any problem with AR being implemented as a base class for your models.</p>

<p>One perceived problem is a lack of separation of concerns, the idea that you should separate model logic and database logic and that ActiveRecords fails here.</p>

<p>But one must look beyond the <em>separation-of-concerns</em> dogma here and ask what motivates this principle. Mixed concerns lead to confusion, confusions leads to errors and redundance (and thus to more errors). So, the motivation is to maintain a clear view over your methods and to reduce redundance.</p>

<p>Both goals are maintained by Rails although the models contain a mix of model- and database logic. Because most things can be expressed <em>very</em> concisely in Ruby, one line or even no code at all (using the powers of reflection) is enough to achieve what you want. If all your model-functionality and ORM-functionality  fit within one page on your screen, the benefit of splitting both into separate modules and/or files becomes too low to justify the cost.</p>

<p>The second problem with inheriting your models from AR::Base is supposedly the tight coupling between your model and your DB-access layer, requiring you to have a database ready for unit testing. If you&#8217;ve ever written tests for Rails, you know this is bullshit. Testing is a non-issue and the support for the testing database so seamless that I can&#8217;t imagine it being any more simple. One rake task sets up your testing database after a migration, the rest is handled automatically.</p>

<p>Pretending that relying on AR so much for your models is still bad somehow because you might want to change your record-store a some point in the lifetime of your application is nothing but a bunch of bullshit. NO solution EVER will enable you to do THAT in a way that&#8217;s so seamless that you&#8217;d want to. We&#8217;re talking about software here, not lightbulbs that you just screw in. Abstractions are always leaky and talking as if they were not is foolish.</p>

<p>The whole point is that Rails set out to to one thing well, and that is to write web apps in a certain way that has proven to be quite productive and covering the needs of most projects pretty well. You get a lot of comfort following that way but you pay a price if you don&#8217;t, namely losing that comfort. People are demanding stuff that Rails never promised to deliver. About their motivations I can only speculate. Maybe they&#8217;re just clueless, maybe they just want to make some noise. In any way, they&#8217;re hell of a reason to <a href="http://gilesbowkett.blogspot.com/2008/05/summon-monsters-open-door-heal-or-die.html">stay away from Digg and Reddit</a> and stick to some bloggers you trust with not wasting your time.</p>
]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/why-bloggers-suck/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails: Determine the association collection size through joins</title>
		<link>http://jan.varwig.org/archive/rails-association-collection-size-though-joins?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rails-association-collection-size-though-joins</link>
		<comments>http://jan.varwig.org/archive/rails-association-collection-size-though-joins#comments</comments>
		<pubDate>Sun, 01 Jun 2008 15:25:21 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[on Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[associations]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[joins]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[rubyonrails]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/?p=82</guid>
		<description><![CDATA[Rails association collections know two ways to determine their size: Through a dumb count as soon as you query the collection for its size. This doesn&#8217;t require any additional work but puts quite a load on the database as soon as you have a large list of objects and want to know the size of [...]]]></description>
			<content:encoded><![CDATA[<p>Rails association collections know two ways to determine their size:</p>

<ol>
<li><strong>Through a dumb count as soon as you query the collection for its size.</strong><br />
This doesn&#8217;t require any additional work but puts quite a load on the database as soon as you have a large list of objects and want to know the size of an associated collection for each object. For 100 posts with comments, this approach would query the database 100 times with <code>SELECT count(*) AS count_all FROM</code>comments<code>WHERE (comments.post_id = 1234)</code>. This might be okay for single objects which are queried from time to time but not for collections that need to be displayed frequently.</li>
<li><strong>Through counter caches that are a bit of a pain in the ass to set up correctly and gave me the fishy impression that they are easily corrupted.</strong>
Now, I admit that I didn&#8217;t spend too long investigating the implementation of the counter cache but after fiddling around with it for an hour before I finally found out how to properly initialize the cache in my migration and after discovering that the cache can only be changed relative to its current content, I left with a bad feeling.<br />
All this hassle is absolutely unavoidable if you need maximum performance. In this article I&#8217;ll use blogposts and comments as an example, though only because this is familiar to many people. A real blog with a bunch of posts on its index page, receiving any considerable amount of hits per day is a bad candidate for the trick I describe here.</li>
</ol>

<p>In raw SQL, if you want to find out the amount of associated rows in a different table, you use a <code>JOIN</code>, combined with <code>COUNT()</code> and <code>GROUP BY</code>, like this:</p>

<div class="dean_ch" style="white-space: wrap;"><span class="kw1">SELECT</span> posts.*, COUNT<span class="br0">&#40;</span>comments.id<span class="br0">&#41;</span> <span class="kw1">AS</span> comments_count<br />
<span class="kw1">FROM</span> posts<br />
<span class="kw1">LEFT</span> <span class="kw1">OUTER</span> <span class="kw1">JOIN</span> comments <span class="kw1">ON</span> posts.id = comments.post_id<br />
<span class="kw1">GROUP</span> <span class="kw1">BY</span> posts.id</div>

<p>Admittedly, this is slower than a counter cache but is not as difficult to set up, doesn&#8217;t risk errors due to a corrupt cache and if you chose your database keys wisely it is a pretty nice compromise.
When you ask an association collection for its <code>size()</code>, rails checks for the presence of a counter cache attribute in the current ActiveRecord object. If it finds one, it uses its content to return the collection size, otherwise the database is queried.</p>

<p>The catch is now, that in the above example, we inserted a perfectly valid counter cache column into our posts without specifying caching in the association declaration in the class. ActiveRecord inserts that columns content into a <code>comments_count</code> attribute in our Posts but since it doesn&#8217;t know exactly what to do with it, it doesn&#8217;t cast it into an integer but leaves it in there as a String. That makes <code>size()</code>, or to be more precise, the <code>count_records()</code> method trip with a &#8220;String can&#8217;t be coerced into Fixnum&#8221; error.</p>

<p>To fix this, I wrote an extension for the has_many Association:</p>

<div class="dean_ch" style="white-space: wrap;"><span class="kw1">module</span> OptionalJoinCounter<br />
&nbsp; <span class="kw1">def</span> count_records<br />
&nbsp; &nbsp; count = <span class="kw1">if</span> has_cached_counter?<br />
&nbsp; &nbsp; &nbsp; <span class="re1">@owner</span>.<span class="me1">send</span><span class="br0">&#40;</span><span class="re3">:read_attribute</span>, cached_counter_attribute_name<span class="br0">&#41;</span>.<span class="me1">to_i</span><br />
&nbsp; &nbsp; <span class="kw1">elsif</span> <span class="re1">@reflection</span>.<span class="me1">options</span><span class="br0">&#91;</span><span class="re3">:counter_sql</span><span class="br0">&#93;</span><br />
&nbsp; &nbsp; &nbsp; <span class="re1">@reflection</span>.<span class="me1">klass</span>.<span class="me1">count_by_sql</span><span class="br0">&#40;</span>@counter_sql<span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="kw1">else</span><br />
&nbsp; &nbsp; &nbsp; <span class="re1">@reflection</span>.<span class="me1">klass</span>.<span class="me1">count</span><span class="br0">&#40;</span><span class="re3">:conditions</span> =&gt; <span class="re1">@counter_sql</span>, <span class="re3">:include</span> =&gt; <span class="re1">@reflection</span>.<span class="me1">options</span><span class="br0">&#91;</span><span class="re3">:include</span><span class="br0">&#93;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="kw1">end</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span class="re1">@target</span> = <span class="br0">&#91;</span><span class="br0">&#93;</span> <span class="kw1">and</span> loaded <span class="kw1">if</span> count == <span class="nu0">0</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span class="kw1">if</span> <span class="re1">@reflection</span>.<span class="me1">options</span><span class="br0">&#91;</span><span class="re3">:limit</span><span class="br0">&#93;</span><br />
&nbsp; &nbsp; &nbsp; count = <span class="br0">&#91;</span> <span class="re1">@reflection</span>.<span class="me1">options</span><span class="br0">&#91;</span><span class="re3">:limit</span><span class="br0">&#93;</span>, count <span class="br0">&#93;</span>.<span class="me1">min</span><br />
&nbsp; &nbsp; <span class="kw1">end</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span class="kw2">return</span> count<br />
&nbsp; <span class="kw1">end</span><br />
<span class="kw1">end</span></div>

<p>Uh, well, yeah, the only change here is the <code>.to_i</code> at the end of line 4 but hey, what did you expect?</p>

<p>Save that in <code>lib/optional_join_counter.rb</code> and extend your association with <code>has_many :whatevers, :extend =&gt; OptionalJoinCounter</code></p>

<p>Now, to get back to the example, imagine we want to use this trick to count our comments.
The above SQL can either be written by hand, or with Rails finder options:</p>

<div class="dean_ch" style="white-space: wrap;">Post.<span class="me1">find</span> <span class="re3">:all</span>,<br />
&nbsp; <span class="re3">:select</span> =&gt; <span class="st0">&#8216;posts.*, count(comments.id) as comments_count&#8217;</span>,<br />
&nbsp; <span class="re3">:joins</span> =&gt; <span class="st0">&#8216;LEFT JOIN comments ON posts.id = comments.post_id&#8217;</span>,<br />
&nbsp; <span class="re3">:group</span> =&gt; <span class="st0">&#8216;posts.id&#8217;</span></div>
]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/rails-association-collection-size-though-joins/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>REST in Place</title>
		<link>http://jan.varwig.org/archive/rest-in-place?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rest-in-place</link>
		<comments>http://jan.varwig.org/archive/rest-in-place#comments</comments>
		<pubDate>Sun, 23 Dec 2007 13:57:01 +0000</pubDate>
		<dc:creator>Jan</dc:creator>
				<category><![CDATA[on Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[inplace editor]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[rubyonrails]]></category>
		<category><![CDATA[web-2.0]]></category>

		<guid isPermaLink="false">http://jan.varwig.org/archiv/rest-in-place</guid>
		<description><![CDATA[In Ajax vs. REST I wrote about my ideas for a RESTful inplace editor. Well, after a day playing around with jQuery, I present REST in Place]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://jan.varwig.org/archiv/ajax-vs-rest">Ajax vs. REST</a> I wrote about my ideas for a RESTful inplace editor.</p>

<p>Well, after a day playing around with jQuery, I present <a href="http://jan.varwig.org/projects/rest-in-place">REST in Place</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jan.varwig.org/archive/rest-in-place/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

