Rails 2.1 Features: Change in find :include behavior

Interesting enough someone had mentioned this change to me over breakfast today but it was the first I had heard of it. That’s unfortunate because it was a change that ended up breaking my code. The jist of it is that when using an include parameter for finds Rails no longer just creates a join query. I agree that this is advantageous is many situations that are common for Rails apps but it neglects when you actually want to have a condition for the joined table. Thankfully it’s not too difficult to get the original behavior back by simply qualifying the column with its table name. I found some helpful details from these posts:

Update: The pluralization is tricky on these. The include must be the name of the association which is plural for has_many and singular for belongs_to. However the qualification must be the table name which is plural. Here is an example.

Hopefully these examples illustrate the subtle difference. Also the include parameter does not have to be an array of 1 item, it can just be that item itself by simply removing the brackets.

  • Post.find :all, :include => [:comments], :conditions => ['comments.moderated = ?', true]
  • Comment.find :all, :include => [:post], :conditions => ['posts.active = ?', true]

Trackback URL for this post:

http://hightechsorcery.com/trackback/141
Creative Commons License Except where otherwise noted, content on this site is licensed under a Creative Commons by-nc-sa 3.0 License