Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

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

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:

Thursday:

Comments
Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *