Why does the Rails increment method doesn't save the changes?

1.3k Views Asked by At

I have this code to implement a thumbs up/down functionality in my rails app

if params[:vote][:type] == "up"
    answer = Answer.find_by_id(params[:vote][:id])
    answer.increment(:ups)
    render text: answer.ups
end
if params[:vote][:type] == "down"
    answer = Answer.find_by_id(params[:vote][:id])
    answer.increment(:downs)
    render text: answer.downs
end


It doesn't give any error but the incremented value is not updated in the DB.

This code works properly in rails console.

Please help,

Thanks in advance

3

There are 3 best solutions below

6
On BEST ANSWER

could you please write the schema of your model, I mean fields with datatype

another migration with:

change_column :answers, :ups, :integer, :default: 0
change_column :answers, :downs, :integer, :default: 0

might help you

1
On

Check it once

if params[:vote][:type] == "up"
    answer = Answer.find_by_id(params[:vote][:id])
    answer.to_i.increment(:ups)
    render text: answer.ups
elsif params[:vote][:type] == "down"
    answer = Answer.find_by_id(params[:vote][:id])
    answer.to_i.increment(:downs)
    render text: answer.downs
end
2
On

this is by design. The method increments the attribute but does not save. Use increment! (bang version) if you want to save as well.