Forum: Ruby on Rails Can somebody explain when to reload an ActiveRecord

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9ca332fe62891e975ad6e70aca9fb958?d=identicon&s=25 Jack Hung (Guest)
on 2006-01-10 11:24
(Received via mailing list)
Hi all,

I've the following test method in my controller_test which increment the
'qty' attribute in a has_many association, 'sa_report_products'. The
'item_count' method returns the sum of all qty's in
'sa_report_products':

  def test_add_product_to_report
    sa_rpt = SaReport.find(1)
    assert_equal 3, c = sa_rpt.item_count, 'initial count is 3'
    assert_equal 2, sa_rpt.sa_report_products[0].qty, 'initial qty is 2'
    post :add_item, :id => sa_rpt.id, :new_product_item_id => 1,
:new_product_item_qty => 3
    sa_rpt.reload  # MUST HAVE THIS TO WORK, WHY??
    assert_equal 2, sa_rpt.sa_report_products.length, 'still have 2 item
lines'
    assert_equal 5, sa_rpt.sa_report_products[0].qty, '3 added'
    sa_rpt.update
    assert_equal c + 3, sa_rpt.item_count, '3 added'
  end
end

The test failed if I leave out the "sa_rpt.reload" line, that is
"sa_rpt.sa_report_products[0].qty" is still 2, not 5.

My problem is I don't really understand when I needed to reload an
ActiveRecord, can somebody explain?

Thank
Jack Hung
34791e1d8c4def65f9b93294638a7e04?d=identicon&s=25 Joerg Diekmann (joergd)
on 2006-01-10 12:22
You generally use the Reload method in your test harnesses. You have set
sa_rpt to the item with id=1. After the post, the data inside the
database has changed wrt to id=1. sa_rpt does not re-populate itself
automatically if the database changes, so you need to do a Reload to get
the latest data from the database if you want to make use of the new
data - which you are because you want to run tests against this data.
This topic is locked and can not be replied to.