rails5中临时修改AR实例的关联对象集合

ruby

class User
    has_many :posts
end

class Post
    belongs_to :user
end

直接修改会操作db

User.first.posts # => return Post::ActiveRecord_Associations_CollectionProxy < ActiveRecord::Associations::CollectionProxy

User.first.posts = []  #=> 会调用 before_remove_for_posts 和 after_remove_for_posts 方法,对db进行操作

最终通过这种方式修改target,成功

user = User.first
user.posts.load_target
user.posts.instance_variable_get('@association').instance_variable_set("@target", [])

user.posts # => []

发表于 2020.02.22