【问题标题】:Fill in unfilled properties with other model用其他模型填充未填充的属性
【发布时间】:2012-04-21 18:42:34
【问题描述】:
我有一个 ActiveRecord 模型 @new_profile,其中填充了一些但不是所有属性。我有另一个模型 @default_profile,它有一堆我想要复制的值,但前提是来自首先没有填写。除了像...这样的块之外,还有内置的方法可以做到这一点。
@new_profile.name ||= @default_profile.name
@new_profile.address ||= @default_profile.address
# etc.
【问题讨论】:
标签:
ruby-on-rails
ruby
activerecord
ruby-on-rails-3.1
【解决方案1】:
这可能有效
@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))
【解决方案2】:
@new_profile.update_attributes(@default_profile.attributes.merge(@new_profile.attributes))
【解决方案3】:
你可以试试
@new_profile.attributes = @new_profile.attributes.reverse_merge @default_profile.attributes
【解决方案4】:
如果您需要复制所有属性(当然id 除外):
@new_profile.attributes.each{|k,v| @new_profile[k] ||= @default_profile[k] if k != 'id'}
update_attributes 之类的内容不允许您复制 attr_protected-attributes。 这东西应该。