2012-04-21 54 views
0

我有一个ActiveRecord模型@new_profile有一些,但不是所有的属性填写。我有另一个模型@default_profile有一堆我想复制的值,但只有当从第一属性不填充。有一个内置的方式做到这一点,除了块像...填写与其他模型的未填充的属性

@new_profile.name ||= @default_profile.name 
@new_profile.address ||= @default_profile.address 
# etc. 

回答

0

你可以尝试像

@new_profile.attributes = @new_profile.attributes.reverse_merge @default_profile.attributes 
0
@new_profile.update_attributes(@default_profile.attributes.merge(@new_profile.attributes)) 
1

这可能会实现

@new_profile.update_attributes!(@default_profile.attributes.merge(@new_profile.attributes)) 

的问题与此是,如果该属性是@new_profile,但它是零,合并可能会留下设为零值。您可能需要执行以下操作。

new_profile_attrs = @new_profile.attributes.reject{ |key,value| !value } 
@new_profile.update_attributes!(@default_profile.attributes.merge(new_profile_attrs)) 
0

如果你需要复制的所有属性(当然除了id):

@new_profile.attributes.each{|k,v| @new_profile[k] ||= @default_profile[k] if k != 'id'} 

之类的东西update_attributes不会让您复制attr_protected -attributes。 这个东西应该是