The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Conditional Association Loading Trick

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Obie Fernandez

Posts: 608
Nickname: obie
Registered: Aug, 2005

Obie Fernandez is a Technologist for ThoughtWorks
Conditional Association Loading Trick Posted: Apr 24, 2007 5:39 PM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Obie Fernandez
Latest Posts From Obie On Rails (Has It Been 9 Years Already?)

Advertisement

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 :neighborhoods  do
  def loaded?
    return true if (proxy_owner.population.nil? or proxy_owner.population < 50000)
    super
  end
end

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.

def loaded?
  (proxy_owner.population.nil? or proxy_owner.population < 50000) ? true : super
end

Read: Conditional Association Loading Trick

Topic: Is This a Bad Idea? Previous Topic   Next Topic Topic: Aptana backs RDT, hires me

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use