我有一個ActiveRecord模型@new_profile
有一些,但不是所有的屬性填寫。我有另一個模型@default_profile
有一堆我想複製的值,但只有當從第一屬性不填充。有一個內置的方式做到這一點,除了塊像...填寫與其他模型的未填充的屬性
@new_profile.name ||= @default_profile.name
@new_profile.address ||= @default_profile.address
# etc.
我有一個ActiveRecord模型@new_profile
有一些,但不是所有的屬性填寫。我有另一個模型@default_profile
有一堆我想複製的值,但只有當從第一屬性不填充。有一個內置的方式做到這一點,除了塊像...填寫與其他模型的未填充的屬性
@new_profile.name ||= @default_profile.name
@new_profile.address ||= @default_profile.address
# etc.
你可以嘗試像
@new_profile.attributes = @new_profile.attributes.reverse_merge @default_profile.attributes
@new_profile.update_attributes(@default_profile.attributes.merge(@new_profile.attributes))
這可能會實現
@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))
如果你需要複製的所有屬性(當然除了id
):
@new_profile.attributes.each{|k,v| @new_profile[k] ||= @default_profile[k] if k != 'id'}
之類的東西update_attributes
不會讓您複製attr_protected
-attributes。 這個東西應該是。