rails在保存时创建重复的对象

时间:2014-10-24 09:48:47

标签: ruby-on-rails ruby-on-rails-4

我有一个模型Game,可让您选择包含许多Character的{​​{1}}。此角色是原型,不应更改其属性。 我想创建一个新的Char_Attributes,让玩家选择原型字符,然后创建此字符属性Game的副本,以便在游戏过程中重复的角色的属性可以改变。

我想它应该有点像这样:

(:game_id => game.id)

但是(假设这接近可用的语法)我会把它放在哪里?这是一个很好的方法吗?

我很感激你能给我的任何提示!

2 个答案:

答案 0 :(得分:1)

创建属于您的游戏和用户的GameCharacter模型,该模型由所选原型的属性实例化,但与原型没有实际关系。

您的方法将类似于:

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

这样,您就可以将ArchetypeCharacter属性复制到GameCharacter

答案 1 :(得分:0)

感谢Matt我无需创建新模型即可找到解决方案,我将新的Char_attributes直接分配给我新建的游戏添加:

initialise_game_character(@game,@ game.character_id)

在游戏控制器中&#34;创建&#34;我把方法改为:

def initialise_game_character(game,archetype_character_id)     game_character = Character.create(游戏:游戏)

  Charattribute.where(:character_id => archetype_character_id).each do |archetype_char_attribute|
    game.charattributes << Charattribute.new(:name => archetype_char_attribute.name, :value => archetype_char_attribute.value)
  end    
end

非常适合我想做的事情!