4

我有一个模型,代表一个包含很多条目的定价表,我想提供使用现有条目中的值创建新定价的可能性。

有谁知道如何做到这一点,然后续集正在使用中?

我尝试了 dup 和 clone 但在这两种情况下,现有模型中的 id 仍然存在,因此将更新现有条目。

如果我尝试手动设置 id,我会收到以下错误:

Sequel::InvalidValue: nil/NULL is not allowed for the id column

所以我需要找到一种方法来创建一个新的但具有预填充值的模型,而无需手动在代码中设置它们。

有任何想法吗?

4

2 回答 2

4

找到了:

new_pricing = Pricing.new(oldprice.attributes.tap{|attr| attr.delete("id")})

我从旧模型中获取属性作为哈希,然后删除 id 并通过传递除 id 之外的属性来创建新模型。

于 2012-10-29T21:29:50.413 回答
-1

model.attributes解决方案对我不起作用。续集模型to_hash大致等效,但to_hash不返回反序列化值。如果您正在使用序列化程序(用于jsonb字段等),只需将 a 传递to_hashnew将失败,因为这些值尚未反序列化。

这是对我有用的解决方案:

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
于 2016-02-16T15:50:55.660 回答