我有链接(S3)关联到它如何在更新父对象属性后自动清理孤儿?
class User < ActiveRecord::Base
has_many :images, :dependent => :destroy
# left out other attributes for simplicity of the example
end
class Image < ActiveRecord::Base
belongs_to :user
attr_accessible :url, :name, :bucket
end
图像的用户模型我有一个JSON API更新的图像(/用户/:ID)。使用JSON身体一个例子POST请求是这样的:
{
"user": {
"images": [
{
"name":"Fun pic",
"bucket":"pix3.mydomain.com"
},
{
"name":"Hilarious pic",
"bucket":"pix2.mydomain.com"
}
]
}
}
我要覆盖所有图像与这个新的数组用户,而无需离开旧图像的跟踪数据库。
目前,我通过使用Image.create(hash)将数组中的所有图像哈希值映射到Image对象。我们调用结果数组'new_images'。然后我调用User.update_attributes({“images”=> new_images})。用户现在将分配正确的图像给他,但之前的图像仍然在数据库中浮动。
所以,我正在寻找一种简单的方法,用新对象替换has_many关联中的所有对象,而不会在数据库中留下旧对象。当然,我可以创建一个事务,首先删除所有旧图像,然后分配新图像,但它看起来像很多样板。对此有何想法?
试过这个,它按预期工作:)我使用user.update_attributes(散列),因为'散列'可以包含很多更新的属性在我的情况。对于has_many关系,我现在使用显式赋值并使用user.update_attributes(hash.except(“images”))过滤这些键。 –