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

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Jack Hung (Guest)
on 2006-01-10 12: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

  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 =>, :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
    assert_equal 5, sa_rpt.sa_report_products[0].qty, '3 added'
    assert_equal c + 3, sa_rpt.item_count, '3 added'

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?

Jack Hung
Joerg D. (Guest)
on 2006-01-10 13: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.