Ruby on rails 用其他模型填充未填充的属性

Ruby on rails 用其他模型填充未填充的属性,ruby-on-rails,ruby,activerecord,ruby-on-rails-3.1,Ruby On Rails,Ruby,Activerecord,Ruby On Rails 3.1,我有一个ActiveRecord模型@new_profile,它有一些但不是全部的属性。我有另一个模型@default\u profile,它有一堆我想复制的值,但前提是第一个模型的属性没有填写。除了像…这样的街区外,还有没有一种内置的方式可以做到这一点 @new_profile.name ||= @default_profile.name @new_profile.address ||= @default_profile.address # etc. 你可以试试类似的东西 @new_prof

我有一个ActiveRecord模型
@new_profile
,它有一些但不是全部的属性。我有另一个模型
@default\u 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中,但它是nil,则合并可能会将该值设置为nil。您可能需要执行以下操作

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

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

update\u attributes
这样的东西不允许您复制
attr\u protected
-属性这东西应该

new_profile_attrs = @new_profile.attributes.reject{ |key,value| !value }
@new_profile.update_attributes!(@default_profile.attributes.merge(new_profile_attrs))
@new_profile.attributes.each{|k,v| @new_profile[k] ||= @default_profile[k] if k != 'id'}