I want to validate a form that gets submitted. The name of the param that is send is ratings. And that param gets saved in the rating_score column.
I want to validate that the param ratings is only between 1 and 5.
I have put this in my model:
validates_inclusion_of :rating_score, :in => 1..5
After that I submitted my form with the param ratings = 6 and it got saved in my database.
My controller:
def rate
@konkurrancer = Konkurrancer.find(params[:id])
@konkurrancer.rating_score ||= 0
@container = "Konkurrancer"+@konkurrancer.id.to_s
@konkurrancer.rating_score += params[:vind][:ratings].to_i
@konkurrancer.ratings += 1
@konkurrancer.save
respond_to do |format|
format.js
end
end
My model:
class Konkurrancer < ActiveRecord::Base
attr_accessible :rating_score
validates_inclusion_of :rating_score, :in => 1..5
end
My log when submitting my form:
Started POST "/konkurrancers/rate/7" for 127.0.0.1 at 2011-05-03 23:23:53 +0200
Processing by KonkurrancersController#rate as */*
Parameters: {"utf8"=>"Ô£ô", "authenticity_token"=>"h6RSZbuVVfYIvdNb31xS6Oo7Q8o
1JxvVL24aoJ2GQ/o=", "vind"=>{"ratings"=>"6"}, "id"=>"7"}
Completed 200 OK in 488ms (Views: 239.0ms | ActiveRecord: 20.0ms)
How to do the validation?
Try to save it before render view. Looks like your object is not saved, but your
rating_scoreis dirty and equal 6.OLD
Ok you are validating
rating_scorebut notraitingsSo if you set
ratings = 6it will saved.But if you will set
rating_score = 6it won’t be saved, because your validation is right.Try this
or