1
class Game
  has_many :players, dependent: :destroy
end

class Player
  belongs_to :game
end

Let's say we have one game and three players associated to it.

How do we duplicate these four records in the most succinct way, without any use of gems?

Here are two questions on SO around the same subject, but are either utilizing gems or seem overly complex.

Community
  • 1
  • 1
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

1 Answers1

2

This piece of code can be a start:

class Game
  has_many :players

  def clone
    attributes = self.attributes
    ['id', 'created_at', 'updated_at'].each do |ignored_attribute|
      attributes.delete(ignored_attribute)
    end
    clone = Game.create(attributes)
    self.players.each do |player|
      player.clone.update_attributes(game_id: clone.id)
    end

    clone
  end
end

class Player
  belongs_to :game

  def clone
    attributes = self.attributes
    ['id', 'created_at', 'updated_at'].each do |ignored_attribute|
      attributes.delete(ignored_attribute)
    end
    clone = Player.create(attributes)

    clone
  end
end

with this, you could create a module acts_as_clonable, and include it in your models, with some options:

class Game
  has_many :players

  acts_as_clonable relations: [:players], destroy_original: false, ignored_attributes: [:this_particular_attribute]

If you have the ambition, you could make a Gem with this... ;-)

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117