perfectline/validates_url

Local/relative url as fallback

Closed this issue · 3 comments

Have used this gem for other url fields but the current field I'm trying to apply it to allows the user to specify a url for an image and if none is set then it uses a local fallback placeholder image which is set using the default value on the database field.

I set the object to not pass a value in for this url and it should then use the db default value.

It is doing it fine, it's only the validation that's failing when I apply it because it says /images/default.png is not a valid url.

Is there a way I can specify this using the gem or do I have to roll my own validation somehow for this particular field?

default value in the DB is not what you want to do. What you want to do is to use either decorator (like draper gem) or not so nice code but still working

class MyRecord < ActiveRecord::Base
def name
  super || "/images/default.png"
end
end

Thanks @kritik I'll give that a whirl.
I think the easiest is possibly to use the "not so nice code but still working" so that it will be available whether accessed on the site or the via API (although for the API I'd probably need to make it a full/absolute url).

@kritik not quite easy to use a url since the API would need to provide an absolute url and that changes between the dev and production environments.
The validation is also being called on the field when clicking save and with a relative '/images/default.png' it fails validation as before.
I think this leaves me using a view helper or decorator instead then and use a separate one for the API with the full url.