开发者

Rails help to validate number

开发者 https://www.devze.com 2023-03-02 20:04 出处:网络
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 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 use validates_numericality_of

validates_numericality_of :ratings , :less_than_or_equal_to=>5, :greater_than_or_equal_to=>1


Try to save it before render view. Looks like your object is not saved, but your rating_score is dirty and equal 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

OLD

Ok you are validating rating_score but not raitings

So if you set ratings = 6 it will saved.

But if you will set rating_score = 6 it won't be saved, because your validation is right.

Try this

class Konkurrancer < ActiveRecord::Base
  attr_accessible :rating_score
  validates_inclusion_of :rating_score, :in => 1..5
end

or

class Konkurrancer < ActiveRecord::Base
  attr_accessible :rating_score
  validates :rating_score, :inclusion => { :in => 1..5 }
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号