Search code examples
ruby-on-railsattributesupdate-attributes

How do I add an integer to an attribute using a form in rails?


I have a form that takes in an integer for a user attribute called calories: and I want the input integer to be added to the current value, not replace it. So my question is basically: how do I take the form input value and use it to increase the number of calories?

Ok so here is the form in my users/show view:

<div class="row"> <div class="col-md-8"> <%= form_for @user do |f| %> <div class="form-group"> <%= f.label "Add calories" %> <%= f.number_field :calories, class: 'form-control'%> </div> <div class="form-group"> <%= f.submit "Add", class: 'btn btn-success' %> </div> <% end %> </div> </div>

and my update action in my users_controller:

def update
  @user = current_user
  @user.assign_attributes(user_params)
end

private

def user_params params.require(:user).permit(:calories) end


Solution

  • So presumably you have an @user object and a params[:calories] value(Your names may be different). In your update action you will do this:

    previous_calories = @user.calories
    final_calories = previous_calories + params[:calories]
    @user.update_attributes(calories: final_calories)
    

    That is how to do it on a high level. I would actually extract this into a model method on user like this:

    def update_calories(calories)
      previous_calories = self.calories
      total_calories = previous_calories + calories
      self.update_attribute(calories: total_calories)
    end