Callum Rogers
Callum Rogers

Reputation: 15829

Best way to update an ActiveRecord attribute from a link

I have a Model with an attribute votes. I have a link in a view that needs to increment the value of votes - what is the best way to do this?

I am currently trying a link like:

<%= link_to 'Up', '#', :method => :voteup %>

and a voteup method in the model_controller but this isn't working.

Upvotes: 0

Views: 184

Answers (2)

Andy Lindeman
Andy Lindeman

Reputation: 12165

I think the best way would be this:

In config/routes.rb:

resources :quotes do
  member do
    post :upvote
  end
end

And your link:

<%= link_to 'Up', upvote_quote_path(@quote), :method => :post %>

Note that we use a POST request, which is more appropriate than a GET request when modifying a record.

Upvotes: 3

Dylan Markow
Dylan Markow

Reputation: 124419

:method is only supposed to be used to specify between POST, GET, DELETE, and PUT requests. Your second parameter of link_to should be the action you want to execute in your controller.

<%= link_to "Up", :action => :voteup %>

Upvotes: 1

Related Questions