在Rails 3.2.16中,我们在查询关联时将关联为用户has_many活动has_many,我们可以通过使用不会更新数据库的 pop 方法分离内存中的关联,一旦我们重新加载主对象,它将删除内存中的更改。
**Rails 3.12.16**
@user = User.find(1) # Identifying the user
@user.activities # Fetching activities of that user having one record
[#<Activity id: 205501, title: "Logging", user_id: 1, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]
@user.activities.pop # will detach the first object and @activities will have an empty array in the whole application until reloading main object
[]
@user.activities # will return []
@user.activities.build(id: 1234567, title: "Signing Out") # will return only new built object
[#<Activity id: 1234567, title: "Signing Out", user_id: 1>]
@user.reload
@user.activities # will retain the association records
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]
**Rails 4.2**
@user = User.find(1) # Identifying the user
@user.activities # Fetching activities of that user
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]
@user.activities.pop # will throw an error because ActiveRecord::CollectionProxy is not having the pop method
# So we tried the to_a method
@user.activities.to_a.pop # it is affecting the array but not detaching the association in memory due it is not mutated
[]
@user.activities # > Rails 4 the association is reloaded defaultly
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]
# If we are trying to build a new object
@user.activities.build(id: 1234567, title: "Signing Out")
@user.activities # We are receiving both existing and new build object but we needed only newly build object like rails 3
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">,
#<Activity id: 1234567, title: "Signing Out", user_id: 1>]
正如 Rails Document 建议使用 delete 方法, 但它正在更新数据库中的关联记录并删除该记录。 任何人都可以建议在 rails 4.2 中更换 rails 3.12.16 pop 方法
目前,我们正在将Ruby on Rails应用程序从3升级到4,2。
宝石列表:-
Rails 4.2.0 -
1) ruby (2.3.3)
2) activerecord (4.2.0)
Rails 3.2.16 -
1) ruby (2.0.0)
2) activerecord (3.2.16)
根据一个 rails 贡献者的说法,这是预期的行为。
看这里: https://github.com/rails/rails/issues/30612#issuecomment-329884753
我怀疑你将不得不找到一种不同的方式来做你想做的事情,但你还没有真正说明你想要完成什么。