Reputation: 4617
Let's say I'm keeping track of a character's health in my HP model.
I have HP.min, HP.max and HP.current, three attributes which track the characters minimum HP, maximum HP and current HP respectively.
I have a form that allows players to input their minimum and maximum HP. I'd like to then set HP.current to the value of params[:max] upon creation, as having the player entire the same value for their current and maximum HP seems super redundant.
What's the best way to accomplish this? I've tried a few ActiveRecord callbacks (after_save, before_create), but have had no luck.
Upvotes: 2
Views: 924
Reputation: 8202
Either do it in the model:
before_save { |hp| hp.current = hp.max }
Or do something in the controller:
def update
@hp.current = params[:max] if params[:max]
if @hp.update_attributes(params[:hp])
# your options here
else
# your options here
end
Upvotes: 1
Reputation: 329
How are you currently using the callbacks? Perhaps you could post some code so we could see if there is a problem with the implementation. :)
Alternatively, I assume that the form values would be passed to a controller and you could build the record manually by setting max => params[:max], current => params[:max]
before saving the record.
Upvotes: 1