在两个ActiveRecord类之间合并/复制属性的好方法?

gar*_*man 5 ruby ruby-on-rails-3

这已被要求部分之前,我发现下面的剪辑如何一次性设置所有类对象的属性,但它是不可能的,因为大量分配保障轨.(例如,你不能Object.attributes = {})

有没有一种很好的方法将属性从一个类合并到另一个类?

object1.attributes = object2.attributes.inject({}){ |h,(k,v)|
  h[k]=v if ObjectModel.column_names.include?(k); h
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Mat*_*ins 13

assign_attributes:without_protection选项一起使用.

attributes = object2.attributes.select do |attr, value|
  ObjectModel.column_names.include?(attr.to_s)
end
object1.assign_attributes(attributes, :without_protection => true)
Run Code Online (Sandbox Code Playgroud)

  • 更好的是:attributes = object2.attributes.slice(*ObjectModel.column_names)object1.assign_attributes(attributes,without_protection:true) (4认同)
  • 以及从object2获取属性的一种更简洁的方法:`attributes = object2.attributes.select {| attr,value | ObjectModel.column_names.include?(attr.to_s)}` (2认同)