Pivotal Labs

Main menu

Skip to primary content
Skip to secondary content
  • About
  • Case Studies
  • Team
    • Executives
    • Locations
      • San Francisco (HQ)
      • Boston
      • Boulder
      • Denver
      • London
      • Los Angeles
      • New York
  • Community
    • Blogs
    • Tech Talks
    • Events
  • Careers
    • Lifestyle
    • Principles & Practices
    • Benefits
    • FAQ
    • Apply
  • Contact
    • Press Room
    • Press Releases
    • In The News
    • Press Kit
  • All
  • Labs
  • Standup
  • Tracker

NYC Standup 04/24/2012: Loading OBJECTS through associations..

Cathy O'Connell
Tuesday, April 24, 2012

Interesting Things

  • When you load objects through associations, you should be aware of how the objects are being loaded. If a where statement is used the calls are being translated to SQL and always hitting the database.

example

it "should whatever" do
      foo.bars.where(something: true).each { |bar|        bar.modify_something }
      foo.bars.each { |bar| bar.expect_something_to_be_modified }
end
  • This will fail as the first call is not only limiting the association but also loading different objects to the second foo.bars collection.

  • Choosing first on a has_many association is dangerous. There are two ‘first’ functions a class and an array one. Depending on whether the association is loaded, a different method is called.

example

it "should do something with the first element" do
    foo.bars.first.modify_something
    foo.bars(:force_load).first
end
  • To ensure loading occurs and thus the object is the same on every call, you can provide any value that evaluates to true as part of the association call. Here :force_load symbol, evaluates to true and forces a database load for bars.

Events This Week

Tuesday:

  • 12:30- Brownbag
  • 6:30- NYC.rb Hackfest

Thursday:

  • 6:30- NYC Ruby Women Hackfest + Chat
  • 0 Shares
  • Share on Facebook
  • Share on Twitter

Add New Comment Cancel reply

Your email address will not be published.

Cathy O'Connell

Cathy O'Connell
New York

Recent Posts

  • NYC Stand-up Wednesday 26th September
  • Standup NYC – CSS Image History
  • NYC – 11/04/2011: Validating and Font face serving
Subscribe to Cathy's Feed

Author Topics

agile (5)
association loading (1)
  • About
  • Case Studies
  • Team
  • Community
  • Careers
  • Contact
  • Labs
  • Events

Contact Us

contact@pivotallabs.com
+1 415-77-PIVOT
TwitterLinkedInFacebook

Pivotal Tracker

Tracker is the award-winning agile project management tool that enables real-time collaboration around a shared, prioritized backlog.
Visit pivotaltracker.com >