user315252
user315252

Reputation: 179

Updating an attribute

I need to update an attribute in a model with an integer value (For ex 1,2,3) with a click of an button. What is the best way to achieve this? can I pass the integer value and update the model or how to achieve this? I need to put a method in my controller which takes the integer?

Upvotes: 0

Views: 511

Answers (1)

Gerry
Gerry

Reputation: 5336

Well as I understand you want to update an attribute of an already initialized instance of a Model, lets say @model = Model.first

---- VIEW ----

<%= button_to "Press me",:controller => "models", :action => "change_attr", :attr => 2, :id => @model.id %>

--- CONTROLLER ----

def change_attr
  @model = Model.find(params[:id])
  if @model.update_attributes(:attr => params[:attr])
     # Do some success stuff
  else
     # Do some failure stuff
  end
end

The button_to helper generates a mini-form that let you make a post request to the models controller. I hope I helped.

Upvotes: 2

Related Questions