Vinay Vinay - 12 days ago 10
Ruby Question

how can restrict my field should accepts only numbers in rails?

I am using

text_field
and
number_field
for one field. This field changes depends upon the
question_type
selected. The
number_field
is working fine in
chrome
. It accepts only
number
in
chrome
and not in
mozila
and
IE
.

How can I create a method in model or how can i tell that
:answer_no
should be only
numbers
(1, 0.1, or any numbers not integers). It should not accept string.

<% if question_type == 'C' %>
<%= f.text_field :answer_no %>
<% elsif (question_type == 'T') and (question_type == 'F') and (question_type != 'C') and (question_type != 'Y') and (question_type != 'Z') %>
<%= f.number_field :answer_no %>
<% end %>


Thank you in advance

Answer

Thanks for the Ideas friends. But I made it simple by your ideas.

validates :answer_no, numericality: true, :if => :answer_cannot_be_string?


def answer_cannot_be_string?
  not (question_type.in? %w{ C Y Z })
end

So, Its accepts the decimal and numbers by the question types. I did from the ideas of your answers. So I put +1 to both of you. Thank you.

Comments