我有一個模型Foo
其中:has_many bars
,最初我創建並保存Foo
foo
實例。看着foo.bars
它是空的如預期。但是在創建bar
實例後,belongs
到foo
實例。 foo.bars
不應該是空的,但它仍然是。如果我做Foo.find(foo.id).bars
,它會按預期返回一個非空結果。有沒有辦法update
foo
,這樣我就不必這樣做了。謝謝!更新模型的關聯時,關聯獲取/刪除
0
A
回答
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)
。
相關問題
- 1. 獲取模型的關聯
- 2. 如何獲取與模型關聯模型相關的模型?
- 3. Rails嵌套模型 - 刪除關聯
- 4. 從關聯模型中刪除
- 5. 刪除主要模型條目時刪除關聯表格行
- 6. 更新軌道中的關聯模型
- 7. 的Rails 3更新關聯模型
- 8. 從關聯模型獲取數據
- 9. 導軌關聯的5獲取關聯
- 10. Rails關聯 - 級聯更新
- 11. Primefaces TabView按模型 - 刪除與選項卡關聯的模型
- 12. 關於Rails模型關聯
- 13. 更名爲belongs_to關聯,目前找不到關聯的模型
- 14. CakePHP模型關聯
- 15. 如何訪問關聯模型的關聯模型?
- 16. Rails - 如何在更新父項時刪除關聯的屬性?
- 17. 通過OneToOneField自定義刪除模型和關聯模型
- 18. 迭代has_many時通過關聯訪問關聯模型:通過關聯
- 19. Oracle關聯更新
- 20. 更新關聯表
- 21. 更新刪除相關模型屬性
- 22. 如何使用關聯模型的順序獲取模型?
- 23. Symfony Doctrine:刪除ManyToMany關聯
- 24. Link_to刪除多態關聯?
- 25. 從HABTM表刪除關聯
- 26. Unidirectionnel關係:刪除級聯
- 27. 2 ActiveRecord的模型關聯
- 28. 關聯模型的問題
- 29. 的Joomla模型關聯
- 30. Rspec的模型關聯