【问题标题】:Clone Sequel Model克隆续集模型
【发布时间】:2012-10-19 05:35:24
【问题描述】:

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

有谁知道怎么做,那么Sequel在用吗?

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

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

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

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

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby clone sequel


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      找到了:

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

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

      【讨论】:

      • 你是怎么得到这些属性的? Sequel::Model 对象中没有这样的方法
      • 对不起,我们有某种模型可以实现 AR 具有但在 Sequel 中缺失的方法,请尝试:values.with_indifferent_access
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      相关资源
      最近更新 更多