1

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

MarkoHiel
  • 15,481
  • 2
  • 21
  • 29
Akshay Takkar
  • 500
  • 1
  • 7
  • 21

3 Answers3

3

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

m_x
  • 12,357
  • 7
  • 46
  • 60
  • the increment! method returns true still the DB doesn't reflect the changes – Akshay Takkar Jun 05 '13 at 10:42
  • if it does not act as documented, i guess your problem lies somewhere else. Try to increment the thing manually and save. If it does not work, maybe there's a problem with your column definition. – m_x Jun 05 '13 at 10:58
1

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
Ganesh Kunwar
  • 2,643
  • 2
  • 20
  • 36
  • Answer is a model with attributes like answer_data, ups, downs etc..so i can't convert it to integer..i even tried calling answer.save after answer.increment but it still doesn't work – Akshay Takkar Jun 05 '13 at 10:36
1

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

Muntasim
  • 6,689
  • 3
  • 46
  • 69
  • create_table "answers", :force => true do |t| t.text "answer_data" t.integer "ups" t.integer "downs" t.integer "question_id" t.integer "user_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end – Akshay Takkar Jun 05 '13 at 11:11
  • increment/decrement fields should have default value 0 otherwise it wont work – Muntasim Jun 05 '13 at 11:13
  • i've used a method that keeps 0 as the value of up / down. the method is called before saving the model – Akshay Takkar Jun 05 '13 at 11:15
  • Oh yea there's the problem..before saving a method runs that resets the values to 0..sorry..was a silly mistake – Akshay Takkar Jun 05 '13 at 11:17
  • I have tested keeping null as default value. increment! method is working please make sure answer.increment!(:ups) is executed, I mean if params[:vote][:type] == "up" returns true – Muntasim Jun 05 '13 at 11:26
  • yea..ran the migration..everything is working fine..thanks again – Akshay Takkar Jun 05 '13 at 11:35