Field validation

Hi I have a field called "cost":

<%= f.text_field :cost, :size=>2, :maxlength=>4 %>

I want to check that user enter numeral value and this value is integer

In post.rb (model):

    def cost_validate_int       errors.add_to_base("Error message") unless cost.is_a?(Fixnum)       puts "### #{cost}: "+cost.class.to_s     end

When I enter in field 100 I get:

### 100: Fixnum

when I enter 10.1:

### 10: Fixnum

when I enter 'asdf':

### 0: Fixnum

I completely can't understand what happen. In migration:

t.integer :cost

I think ActiveRectord converts value to Fixnum because in migration this field signed as integer

Can I in some way check cost value in model (value should be numeral and integer)?

Thanks in advance!

Stanislav Orlenko wrote:

Can I in some way check cost value in model (value should be numeral and integer)?

Thanks in advance!

validates_numericality_of?

Pale Horse wrote:

Stanislav Orlenko wrote:

Can I in some way check cost value in model (value should be numeral and integer)?

Thanks in advance!

validates_numericality_of?

I use errors.add_to_base because I don't want to show field's name in the error message(i. e. Cost bla bla bla. web site is localized).

How is the string you enter getting into the cost attribute?

Colin

Colin Law wrote:

well… in fact… you did defined it as an “integer” so, dont expect to get any other class thats not Fixnum or Bignum…

but, you can also use some model validations to be sure that the user entered an integer…

try validates_numericality_of :cost

it will stop your user from entering strings…

im not sure how to stop it from entering floats like "10.6", but im sure there’s a simple way of doing it…

you know, you’re programming in ruby on rails, it IS simple.

Sempre Alerta Para Servir,

Lucas Franceschi Equipe de Programação (Automação) SGI Sistemas (049) 9922-3360

try looking Here. Sempre Alerta Para Servir,

Lucas Franceschi Equipe de Programação (Automação)

SGI Sistemas (049) 9922-3360