该model.attributes
解决方案对我不起作用。续集模型to_hash
大致等效,但to_hash
不返回反序列化值。如果您正在使用序列化程序(用于jsonb
字段等),只需将 a 传递to_hash
给new
将失败,因为这些值尚未反序列化。
这是对我有用的解决方案:
user = User.find(id: 123)
# freeze to avoid accidentally modifying the original user
user.freeze
# duplicate the record, deserialize values, and delete the primary key
# deserialization is useful if your model is using jsonb fields
record_copy = user.to_hash.merge(user.deserialized_values)
record_copy.delete(:id)
duplicate_user = User.new
# pass the has via `set_all` to avoid initialization callbacks
duplicate_user.set_all(record_copy)
# ... other important callbacks
duplicate_user.save