deep_cloneable
で何ができる?
モデル単体ではなく、モデルに関連づいたモデルも含めてクローンしてくれます。
使い方は公式に書いてあります。
動作確認バージョン
rails (5.0.0.1)
deep_cloneable (2.2.2)
モデル定義
class Form < ApplicationRecord
has_many :parts
end
class Part < ApplicationRecord
belongs_to :form
has_many :options
has_many :validations
end
class Option < ApplicationRecord
belongs_to :part
end
class Validation < ApplicationRecord
belongs_to :part
end
Form -- Part -+- Option
|
+- Validation
動作確認
form = Form.find(1)
dup_form = form.dup
cloned_form = form.deep_clone include: { parts: [:options, :validations] }
p dup_form
p cloned_form
p dup_form.form_parts
p cloned_form.form_parts
p cloned_form.form_parts.first.form_options
p cloned_form.form_parts.first.form_validations
cloned_form.save
p cloned_form
p cloned_form.form_parts
p cloned_form.form_parts.first.form_options
p cloned_form.form_parts.first.form_validations
output
#<Form id: nil, …, created_at: nil, updated_at: nil>
#<Form id: nil, …, created_at: nil, updated_at: nil>
#<ActiveRecord::Associations::CollectionProxy []>
#<ActiveRecord::Associations::CollectionProxy [#<Part id: nil, form_id: nil, …, created_at: nil, updated_at: nil>, #<Part id: nil, form_id: nil, …, created_at: nil, updated_at: nil>, #<Part id: nil, form_id: nil, …, created_at: nil, updated_at: nil>]>
#<ActiveRecord::Associations::CollectionProxy [#<Option id: nil, part_id: nil, …, created_at: nil, updated_at: nil>, #<Option id: nil, part_id: nil, …, created_at: nil, updated_at: nil>]>
#<ActiveRecord::Associations::CollectionProxy [#<Validation id: nil, part_id: nil, …, created_at: nil, updated_at: nil>]>
#<Form id: 5, …, created_at: "2017-05-02 05:52:43", updated_at: "2017-05-02 05:52:43">
#<ActiveRecord::Associations::CollectionProxy [#<Part id: 17, form_id: 5, …, created_at: "2017-05-02 05:52:43", updated_at: "2017-05-02 05:52:43">, #<Part id: 18, form_id: 5, …, created_at: "2017-05-02 05:52:43", updated_at: "2017-05-02 05:52:43">, #<Part id: 19, form_id: 5, …, created_at: "2017-05-02 05:52:43", updated_at: "2017-05-02 05:52:43">]>
#<ActiveRecord::Associations::CollectionProxy [#<Option id: 25, part_id: 17, …, created_at: "2017-05-02 05:52:43", updated_at: "2017-05-02 05:52:43">, #<Option id: 26, part_id: 17, …, created_at: "2017-05-02 05:52:43", updated_at: "2017-05-02 05:52:43">]>
#<ActiveRecord::Associations::CollectionProxy [#<Validation id: 4, part_id: 17, …, created_at: "2017-05-02 05:52:43", updated_at: "2017-05-02 05:52:43">]>