Railsで関連レコードまで複製する方法です。
単純に複製するには?
dupもしくはcloneを使えばできます。
cloneだとidも入ります。
irb(main):007:0> Customer.first.dup Customer Load (0.3ms) SELECT "customers".* FROM "customers" ORDER BY "customers"."id" ASC LIMIT 1 => #<Customer id: nil, name: "f", tel: "444444444", created_at: nil, updated_at: nil, company: "f", email: nil, ip_address: "::1", code: nil, notified: false, converted_at: nil> irb(main):008:0> Customer.first.clone Customer Load (0.2ms) SELECT "customers".* FROM "customers" ORDER BY "customers"."id" ASC LIMIT 1 => #<Customer id: 1, name: "f", tel: "444444444", created_at: "2017-01-23 14:57:50", updated_at: "2017-01-23 14:57:50", company: "f", email: nil, ip_address: "::1", code: nil, notified: false, converted_at: nil>
でも、これだと関連レコードまでは複製してくれません。
関連レコードまで複製
deep_cloneableを使うとできます。
User.first.deep_clone(include: [:tasks])
みたいな感じで書くと,userにひもづいているtaskまで複製してくれます。
このgemはめちゃくちゃ便利ですよ!
コメントを残す