This post originated from an RSS feed registered with Ruby Buzz
by Obie Fernandez.
Original Post: Conditional Association Loading Trick
Feed Title: Obie On Rails (Has It Been 9 Years Already?)
Feed URL: http://jroller.com/obie/feed/entries/rss
Feed Description: Obie Fernandez talks about life as a technologist, mostly as ramblings about software development and consulting. Nowadays it's pretty much all about Ruby and Ruby on Rails.
Here's a quick tip for optimizing associations that are only used sometimes, based on business logic. You can use this technique to avoid an extra database query when you know that your association should always be empty. The trick is to override the association proxy's loaded? method so that it always returns true, based on given criteria.
The example I can give you is that of cities and neighborhoods. In my current project application, we have determined that we do not want to represent neighborhoods for cities having a population of less than 50,000 people. Here is the code, which relies on ActiveRecord's support for association extension:
has_many:neighborhoodsdo
defloaded?returntrueif (proxy_owner.population.nil? or proxy_owner.population < 50000)
superendend
The association proxy class checks to see if the collection is loaded already whenever you try to access it, so that it doesn't make extra trips to the database. Taking advantage of that fact, you can insert a bit of logic to always return true when certain conditions are met. Of course, don't forget the call to super if the conditions are not met, so that the standard loaded? behavior is executed.
Here is the slightly more condensed and idiomatic version, keeping in mind that my personal preference is to use nil?, even though I don't have to, in order to preserve readability.
defloaded?
(proxy_owner.population.nil? or proxy_owner.population < 50000) ? true : superend