让模型Quote
具有属性[price, description]
让模型Invoice
具有属性[price, description, priority]
让invoice
来自模型Invoice
的对象具有属性{price: 10, description: 'lamp', priority: 10}
invoice = {price: 10, description: 'lamp', priority: 10}
假设我想将invoice
个属性复制到新的quote
。
quote = Quote.new(invoice.attributes)
这会引发priority
在模型Quote
中不存在的错误。
如何将invoice
属性复制到新的quote
,但只复制quote
可以接受的属性?
答案 0 :(得分:20)
您只能select
Quote
拥有的属性:
Quote.new(invoice.attributes.select{ |key, _| Quote.attribute_names.include? key })
As noted by @aceofspades(但不是动态解决方案),您也可以使用ActiveSupport的slice
:
Quote.new(invoice.attributes.slice(*Quote.attribute_names))
答案 1 :(得分:13)
ActiveSupport的切片方法怎么样?
quote = Quote.new(invoice.attributes.slice(:price, :description))
甚至
quote = Quote.new(invoice.attributes.slice(*Quote.accessible_attributes))
答案 2 :(得分:0)
直截了当的方式是这样的:
source = invoice.attributes
target = (source.keys & Quote.attribute_names).inject({}) {|target, key| target[key] = source[key]; target }
quote = Quote.new(target)
答案 3 :(得分:0)
sample_plan = Plan.last # it contains object we want to convert
new_plan = Addon.new(sample_plan.attributes.except(:id)) # remove that particular column which is not common else you can get attribute errors.
new_plan # you can get the copy object with data in new one.