Adam Templeton
Adam Templeton

Reputation: 4617

Rails: How can I set multiple attributes to the same value upon create?

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

Answers (2)

Richard Jordan
Richard Jordan

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

rawfish.dev
rawfish.dev

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

Related Questions