validating input values(integer)

Rails 3.1.3

I have a table 'Contribution' having a column, 'price' which must be integers.

  validate :price => true, :numericality => { :only_intger => true }

then, in creating a new Contribution DB, I need to check the user input values. Of course, if the values are not valid, it needs to stay in the same page showing error messages .

in 'contributions_controller.rb',

    respond_to do |format|       if @contribution.save         format.html { render action: "new", notice: 'Contribution was successfully created.' }         format.json { render json: @contribution, status: :created, location: @contribution }       else         format.html { render action: "index" }         format.json { render json: @contribution.errors, status: :unprocessable_entity }       end     end

hoping that the 'save' method FAILS upon inputing string values, for example.

But interestingly, if I input, say, 'this' in the input form, it directs to the next page and the '0' (an integer, though) value is inserted in the DB. I do not have any default value to 'price'.

Could anyone point out any mistakes that I am making here?

Thanks in advance.

soichi

If you pop open a Rails console and type:

  'this'.to_i

What result do you get?

Yep - zero is an integer. Rails casts the values from params to map to the DB fields, so if you want validate the values the user typed rather than the values Rails has translated them to, you may need to write a custom validation and check the "before_typecast" value.

Hi All

I am a newbie to this community.

I recently published a gem called event_watcher for one of my project

http://github.com/zzurang/event_watcher

It is a simple dsl thing that is designed to help monitor certain function calls

I wonder if I can get some feedback or advise in general

Thanks

Thanks for your reply.

If you pop open a Rails console and type:

  'this'.to_i

What result do you get?

1.9.3-p0 :008 > 'this'.to_i => 0 1.9.3-p0 :009 >

It's zero...it does not seem good at all :wink:

soichi

That's a different thread entirely :wink:

I’m not sure what effect this syntax will actually have, but it’s not the one you’re looking for. The line in your model should look like this

validates :price, :numericality => { :only_integer => true }

(note the plural ‘validates’ rather than ‘validate’ - they do two quite different things!)

–Matt Jones

validates :price, :numericality => { :only_integer => true }

(note the plural 'validates' rather than 'validate' - they do two quite different things!)

I must be blind! It should have been

  validates :price, :presence => true, ...

and plural, yes, it reminds me Rails like plural nouns.

Thanks.

soichi