“What’s New in Edge Rails: Easy Join Table Conditions”

Just came across this new cool feature in edge rails…

For an application with anything above a moderate level of domain complexity it’s quite likely that you’ve had to perform a query utilizing a join table:

class Article < ActiveRecord::Base
belongs_to :user
end

class User < ActiveRecord::Base
has_many :articles
end

# Get all the users that have published articles
User.find(:all, :joins => :article,
:conditions => [articles.published = ?, true])

t always makes me feel slightly embarrassed to have to resort to using String snippets to specify my query logic, and this little bit is no exception. Well, now we can specify conditions on a join table in a more concise manner:

# Get all the users that have published articles
User.find(:all, :joins => :article,
:conditions => { :articles => { :published => true } })

Note how you’re able to specify the join-table conditions as a hash whose key corresponds to the table or association name of the join table? You can now let Rails worry about forming the correct SQL condition even across complex joins.

However, don’t let the ease of this feature make you use it over a properly associated domain-model. For instance, this join query:

# Get all articles for a given user
Article.find(:all, :joins => :user,
:conditions => { :users => { :id => @user.id } })

is more appropriately represented as:

@user.articles

Technorati Tags: , , , ,

Leave a comment