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: