2013-11-20 15 views
1

我有链接(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关联中的所有对象,而不会在数据库中留下旧对象。当然,我可以创建一个事务,首先删除所有旧图像,然后分配新图像,但它看起来像很多样板。对此有何想法?

回答

1

这是从Api dock

collection=objects 

Replaces the collections content by deleting and adding objects as appropriate. If the :through option is true callbacks in the join models are triggered except destroy callbacks, since deletion is direct. 

的文档所以,当你做

user.images = new_images 
user.save 

这将破坏与用户相关联的旧的和在一个事务更新的new_images user_ID的

+0

试过这个,它按预期工作:)我使用user.update_attributes(散列),因为'散列'可以包含很多更新的属性在我的情况。对于has_many关系,我现在使用显式赋值并使用user.update_attributes(hash.except(“images”))过滤这些键。 –

1

我想尝试这种方法:

@user.images.destroy_all #destroy all the images that were associated with the user 
@user.images = new_images #set the new array of images 
@user.save    #commit changes to the object 

可能会有点脏,但肯定会工作。

+0

感谢您的回答。这或多或少是我现在所做的,尽管我基本上使用@ user.update_attributes(hash),因为'hash'可以包含很多更新的属性。 @Vimsha是对的,你不需要明确地破坏图像,AR会为你做这件事。我会接受他的回答。 –