2012-04-02 88 views
0

我有一個模型Foo其中:has_many bars,最初我創建並保存Foofoo實例。看着foo.bars它是空的如預期。但是在創建bar實例後,belongsfoo實例。 foo.bars不應該是空的,但它仍然是。如果我做Foo.find(foo.id).bars,它會按預期返回一個非空結果。有沒有辦法updatefoo,這樣我就不必這樣做了。謝謝!更新模型的關聯時,關聯獲取/刪除

回答

0

問題是foo.bars會被第一次調用緩存。你可以用它來強制刷新使用foo.bars(true)

2

這可能是因爲緩存而發生的。

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>] 

要解決這個問題,您只需創建富的新實例,或者只是重新加載它:

foo.reload 

或者,foo.bars(true)