Reputation: 11082
I have a model Foo
which :has_many bars
, initially I create and save a Foo
instance called foo
. Looking at foo.bars
it is empty as expected. But after I create a bar
instance that belongs
to the foo
instance. foo.bars
should no longer be empty but it still it. If I do Foo.find(foo.id).bars
it returns a non-empty result as expected. Is there a way to update
foo
so that I don't have to do that. Thanks!
Upvotes: 0
Views: 63
Reputation: 1380
That's probably happening because of caching.
foo = Foo.create! #=> executes sql, and caches the result
foo #=> retrieved from cache
foo.bars << Bar.create #=> creates the bar, and associates it with the foo instance
foo.bars #=> retrieves the bars from cache, so it's []
Foo.find(foo.id).bars #=> executes sql, and returns [<bar# id: 1>]
To get around that, you just create a new instance of foo, or just reload it:
foo.reload
Or, foo.bars(true)
.
Upvotes: 2
Reputation: 18988
The problem is that foo.bars would have been cached by the first call. You can force it to refresh using foo.bars(true)
Upvotes: 0