2012-04-21 79 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。 這個東西應該是