我想验证提交的表单。发送的参数名称是ratings。该参数保存在rating_score列中。
我想验证参数评级仅在1到5之间。
我把这个放在我的模型中:Validates_inclusion_of:rating_score,:in => 1..5
之后,我提交了参数为ratings = 6的表单,它被保存在我的数据库中。
我的控制器:
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
我的模型:
class Konkurrancer < ActiveRecord::Base
attr_accessible :rating_score
validates_inclusion_of :rating_score, :in => 1..5
end
我提交表单时的日志:
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)
如何进行验证?
尝试使用validates_numericality_of
validates_numericality_of :ratings , :less_than_or_equal_to=>5, :greater_than_or_equal_to=>1
尝试在渲染视图之前保存它。看起来你的对象没有保存,但是你的rating_score
是脏的,等于6。
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
if @konkurrancer.save
respond_to do |format|
format.js
end
end
end
旧你验证的是rating_score
而不是raitings
所以如果你设置了ratings = 6
,它将被保存。
但是如果你设置rating_score = 6
,它将不会被保存,因为你的验证是正确的。
试试这个
class Konkurrancer < ActiveRecord::Base
attr_accessible :rating_score
validates_inclusion_of :rating_score, :in => 1..5
end
或
class Konkurrancer < ActiveRecord::Base
attr_accessible :rating_score
validates :rating_score, :inclusion => { :in => 1..5 }
end