0

I'm new from rails and I want to do a voting system for my app where user can vote for post that I call "Idee". An user can vote only once for a post and a post can only be upvoted. I defined a column "like" for my post and I did this :

Controller

def upvote
  @idee = Idee.find(params[:id])
  @idee.like += 1
  redirect_to :back, notice: "Thank you for voting!"
end

Routes

get 'upvote' => "idees#upvote"

View

<%= link_to "up", controller: "idees", action: "upvote", id: @idee %>

But it doesn't work, when I click on the "up" link, I can see the sentence "Thank you for voting!" from my controller but the vote is not made.

How can I do to make this work ?

Simon M.
  • 2,244
  • 3
  • 17
  • 34

1 Answers1

3

You should save your object like this

def upvote
  @idee = Idee.find(params[:id])
  @idee.like += 1
  @idee.save
  redirect_to :back, notice: "Thank you for voting!"
end
XavM
  • 863
  • 9
  • 22
  • 1
    Careful with this approach, you might loose votes if two users upvote the same Idee close in time. Please read more about Locking on http://guides.rubyonrails.org/active_record_querying.html#locking-records-for-update – Leonel Galán Jun 05 '15 at 15:53