是否可以使用Rails中的对象更新整个记录?

时间:2018-11-14 19:00:32

标签: ruby-on-rails activerecord

我想知道如果给定一个activerecord对象,我是否可以更新一条记录(整个行)。

类似

Car.find_by(number: 1) = replacement_information_for_car_1

其中replacement_information_for_car_1是一个Car活动记录对象,我想用它来替换表上当前的旧记录。

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

attributes = replacement_information_for_car_1.attributes
attributes.delete('id') # and anything else you don't want/can't be copied
Car.find_by(number: 1).update(attributes)

这不是世界上最可爱的东西,但应该可以解决问题。

答案 1 :(得分:1)

关于ActiveRecord对象的事情是,它们具有您不想覆盖的唯一标识符。您必须分配不带ID的属性,在您的示例中,该ID最有可能是nil

Car.find_by(number: 1).update(replacement_information_for_car_1.attributes.except(:id))

这行很长,可以重构为类似的内容

new_attributes = replacement_information_for_car_1.attributes.except(:id)
Car.find_by(number: 1).update(new_attributes)