Damjan
Damjan

Reputation: 3

rails create duplicates of objects on save

I have a model Game that lets you select a Character that has many Char_Attributes. This character is an archetype and his attributes should not be changed. I want to create a new Game, let the player select an archetype character and then create duplicates of this characters attributes (:game_id => game.id), so that the duplicate character's attributes can change during the game.

I imagine it should work somewhat like this:

@charattribute = Charattribute.where(:character_id => game.character.id)
@attribute.each do |attribute|
  attribute.new(:game_id => game.id, :name => attribute.name, :value => attribute.value)
end

But (assuming this is near to a usable syntax) where would I put this? Is this a good approach at all?

I would appreciate any tips you could give me!

Upvotes: 0

Views: 60

Answers (1)

Matt
Matt

Reputation: 14038

Create a GameCharacter model that belongs to your game and user, that is instantiated by the attributes of the selected archetype but has no actual relation to the archetype.

Your method would then look something like:

def initialise_game_character(game, archetype_character)
  game_character = GameCharacter.create(game: game)

  archetype_character.char_attributes.each do |archetype_char_attribute|
    game_character.char_attributes << CharAttribute.new(archetype_char_attribute.attributes)
  end    
end

This allows your ArchetypeCharacter attributes to be copied to GameCharacter.

Upvotes: 1

Related Questions