A
A
Anton Misyagin2019-04-03 00:01:27
Ruby on Rails
Anton Misyagin, 2019-04-03 00:01:27

How to generally handle javascript null in ruby ​​globally?

There is a great application on rails. There are many controllers, models, a lot of JavaScript code. Suddenly, out of nowhere, a problem came up. I want to solve elegantly without having to refactor many places in the application.
There is a javascript code that passes the contents of some variable through the form to the rail application. Its value may in some cases be: null. Suppose I take no action and send a post request directly to the server with this null.
This value is bumped by the rails validator:
validates :district,
numericality:
{only_integer: true, greater_than_or_equal_to: -1, allow_nil: true}
And voila - we have an error. There would be no error if I replaced null with nil in the browser. Or, in the controller, he manipulated the input parameters and made this replacement. Or somehow replaced the validator. In general, it seems that you need to run through the entire code and make a bunch of changes. Have you encountered this problem, how to solve it in one fell swoop, well, or with minimal effort?
PS Is it
possible to make your own validator like:
allow_null
so that it skips nil values ​​and the string "null"? If this is easy to do, then how to ensure that NULL is written to the database, and not 'null', especially if the field in the database is not string.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2019-04-03
@2ord

In a good way, you need to validate the data on the client side and not allow sending incorrect data.
A quick way to add extra validation is by inserting it before validates :district

validate :check_district_js_null
validates :district,
  numericality: {only_integer: true, greater_than_or_equal_to: -1, allow_nil: true}
def check_district_js_null
  self.district = nil if self.district == 'null'
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question