在 Ruby 中复制 SQL 行

Duplicating SQL Row in Ruby

一个基本的功能,我就是想不通。

我需要将值从一个 MySQL 行复制到一个新行 - 听起来很简单。

我尝试了下面的方法,将 key_tasks 设置为等于克隆的 future_tasks 但不是为每个任务创建新行的预期结果,而是保持相同的 ID,因此不会' 创建一个新行。 @performance_review 与当前正在进行的审核相关,评估[-2] 与上次完成的审核相关。

    @performance_review.key_tasks = appraisals[-2].performance_review.future_tasks.clone
    @performance_review.save

示例行:

539 | test1 | 1 | 130 | 2017-04-07 10:27:42 | 2017-04-07 11:02:10

预计克隆后:

539 | test1 | 1 | 130 | 2017-04-07 10:27:42 | 2017-04-07 11:02:10
540 | test1 | 1 | 131 | 2017-04-07 10:27:42 | 2017-04-07 11:02:10

克隆后的实际值:

539 | test1 | 1 | 131 | 2017-04-07 10:27:42 | 2017-04-07 11:02:10

找到解决方案。似乎 'dup' 不适用于集合。

appraisals[-2].performance_review.future_tasks.each do |t|
    t['future'] = 0
    @performance_review.key_tasks << t.dup
  end

Rails 有一个 exclude 哈希方法。

所以,如果你想克隆除 id 之外的所有内容,你可以使用,

Foo.find(3).attributes.except("id")

例如

Place.first.attributes.except("id")      
#=> {"name"=>"Seyidin dönəri", "address"=>"Lorem ipsum", "photo"=>"http://press24.az/az/uploads/posts/2013-07/1375267965_1362063196_btn-rk-et-dnr.jpg", "phone"=>"+994502113213", "lat"=>"40.78563", "lng"=>"41.98745", "created_at"=>2017-04-04 07:36:21 UTC, "updated_at"=>2017-04-04 07:36:21 UTC} 

然后您可以将此散列传递给模型上的 create 方法。

例如

Place.create hash_above