Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top