0

A basic function that I just can't get my head around.

I need to copy the values from one MySQL row to a new row - sounds easy.

I've tried the below, setting key_tasks equal to the cloned future_tasks but instead of the expected result of creating new rows for each task, it keeps the same ID, and thus doesn't create a new row. @performance_review relates to the current review taking place and appraisals[-2] relates to the last completed review.

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

Example row:

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

Expected after clone:

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

Actual after clone:

539 | test1 | 1 | 131 | 2017-04-07 10:27:42 | 2017-04-07 11:02:10
  • Possible duplicate of [What is the easiest way to duplicate an activerecord record?](http://stackoverflow.com/questions/60033/what-is-the-easiest-way-to-duplicate-an-activerecord-record) – Chowlett Apr 07 '17 at 11:18
  • Similar, although the ID doesn't change, which is the expected result from my question. – Reece Young Apr 07 '17 at 11:26
  • Hang on, are `key_tasks` and `future_tasks` both `:has_many` relations? – Chowlett Apr 07 '17 at 12:15

2 Answers2

1

Found the solution. It seems 'dup' doesn't work on collections.

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

Rails has an exclude method for hashes.

So, if you want to clone everything except id, you can use,

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

e.g.

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} 

Then you can pass this hash to create method on your model.

e.g.

Place.create hash_above
marmeladze
  • 6,468
  • 3
  • 24
  • 45