2012-10-29 134 views
2

我有一个模型来表示包含大量条目的定价表,我想提供使用现有条目中的值创建新定价的可能性。克隆续集模型

有谁知道如何做到这一点,那么续集是在使用?

我尝试了dup和克隆,但在两种情况下,id仍然存在于现有模型中,因此会更新现有条目。

如果我尝试设置手工ID我得到以下错误:

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

所以我需要找到一种方法来创建一个模型,它是新的,但已经预填充值,而不需要设置在手工编码。

任何想法?

回答

0

发现:

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

我从老款车型的属性是哈希,然后取出ID,并通过将属性除ID创建一个新的模型。

+0

你是怎么得到的属性? Sequel :: Model对象中没有这样的方法 –

+0

啊对不起,我们有一些实现方法AR的方法,但在Sequel中缺少方法,请尝试:values.with_indifferent_access – jethroo

-1

model.attributes解决方案对我无效。续集型号有to_hash,大致相当,但to_hash不返回反序列化的值。如果您正在使用序列化程序(对于jsonb字段等),只需将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