Reputation: 360
i have a question about associations in rails. The situation is the following:
Models:
class Character < ActiveRecord::Base
has_one :character_stats
end
class CharacterStats < ActiveRecord::Base
belongs_to :character
end
Now i need to create stats when a new character is created.
What i doo is this at the moment, i feel like this is a workaround with rails. Is there a more "raily" way to do this?
after_save :character_init
def character_init
create_stats
end
def create_stats
stats = CharacterStats.new
stats.character_id = self.id // this bothers me!
stats.save
end
But i feel there should be something like this:
stats.character << self
Thank You in advance :)
EDIT:
here is how my model look in real life:
def create_stats
race_stats = Race.find(race_id).race_stats
class_stats = RaceClass.find(race_class_id).class_stats
stats = CharacterStats.new
stats.character_id = self.id
stats.health = race_stats.health + class_stats.health
stats.mana = race_stats.mana + class_stats.mana
stats.intellect = race_stats.intellect + class_stats.intellect
stats.armor = race_stats.armor + class_stats.armor
stats.magic_resist = race_stats.magic_resist + class_stats.magic_resist
stats.attack = race_stats.attack + class_stats.attack
stats.defence = race_stats.defence + class_stats.defence
stats.save
self.character_stats_id = stats.id
end
Upvotes: 0
Views: 236
Reputation: 1549
first of all if you want to create CharacterStats
after Character
is created use after_create
callback. About your question you can use ActiveRecord methods which looks like create_character_stats
for creating model and build_character_stats
for initializing model. So you can change your create_stats
method to something like this
def create_stats
self.create_character_stats
end
or you can change your after callback to this
after_create :create_character_stats
and then you don't need any method for this, but in this case you don't have ability to pass attributes to model creating.
also this question mentioned here Using build with a has_one association in rails
Upvotes: 2
Reputation: 7288
in rails way you can use the build_association method refer doc. Also the association should be created only when parent object is created so use after_create
callback
class Character < ActiveRecord::Base
has_one :character_stats
after_create :create_stats
def create_stats
state = self.build_character_stats({}) # empty hash as you are not passing any attributes
state.save
end
end
Also, the model name CharacterStats looks plural and that can violate the naming convention and can cause some issue like resolving association class on run time and so.
Upvotes: 1