Rails:使用“attributes”方法将属性从对象复制到另一个对象

时间:2012-03-06 19:26:12

标签: ruby-on-rails ruby activerecord

让模型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可以接受的属性?

4 个答案:

答案 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.