russormes/a2p — pull request #3 by russormes (2014-02-12 17:22:53+00:00)
Title: Add image_path field to pupil records and attempt validation of urls

Bro,

I am currently working locally using a branch called 'create-model' which I just pushed to git-hub. You can see from this comparison what I added yesterday in order to try and validate an image_path field I added to the pupils record.

In the `gemfile` I added `gem 'validate_url'` to include a rails module for checking urls. This then allowed my to add the line `validates :image_path, allow_blank: true, url: true` into the pupils.rb model file.

A second attempt (not related to the above) was to add a 'validator' here: ` app/validators/uri_validator.rb` Putting this file in app/validators makes it available without having to include the file path anywhere in the configuration (i.e. rails already checks for this folder). I then used the following to the model, where the `uri:` hash sets the reg-expression used to check the string is the right format and then the code in the uri_validator.rb should check the url actually points to something.

validates :image_path, allow_blank: true,
uri: { format: %r{/(\z)|(^(http|https):\/\/[a-z0-9]+
([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\z)}ix }

The third attempt was

validates_uri_existence_of :image_path, with:
%r{/(^\z)|(^(http|https):\/\/[a-z0-9]+
([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\z)}ix

This required adding the code in a file `lib/validates_uri_existence_of.rb` and including the name of this file in the `config/environment.rb` with `require 'validates_uri_existence_of'`.

None of these worked! I can set the image_path url to be 'http://ormer.' and it passes the validation, despite the string being turd and not pointing to any real resource. If you look in the `spec/models/pupil_spec.rb` file below you can see I set the image_path value to fail validation and it doesn't.

So I am playing about with that. I know it is not a priority, but if we an figure out stuff like this we are learning rails. The best way to check the url so far is to use

validates :image_path, allow_blank: true, format: {
with: /\.(gif|jpg|png)\z/i,
message: 'URL must point to GIT/JPG/PNG pictures'
}

which just checks to see if the and of the image_path is .jpg or similar!

The uri_validator1.rb and uri_validator2.rb are just other versions of the uri_validator.rb file.