Reputation: 5507
Use validates_url can validate url format.
Set validation in model:
validates :homepage, uniqueness: true, url: true
Can't validate these two cases as unique url:
But they should be the same. If the first one is inserted into database, the second one should be validated and not allow to be inserted.
I didn't find a way to realize it using validates_url
. Is it possible?
Upvotes: 1
Views: 376
Reputation: 340
I do use rubular.com to validate using regex. You can try this ^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\.*)?$
Upvotes: 1
Reputation: 549
So the two validations, uniqueness and URL, happen separately, and there is nothing in the uniqueness check to handle the fact that those two URLs are essentially the same - instead, the string values are technically different, and thus it doesn't trip the uniqueness validation.
What you could do is look to tidy up your URL data before validation, with a before_validation
callback in your model:
before_validation :process_url
def process_url
self.homepage = self.homepage.slice(0, self.homepage.length - 1) if self.homepage.present? && self.homepage.ends_with?("/")
end
This is called before the validations kick in, and will make sure that if the homepage attribute is present (even if you add a presence validation later if it becomes non-optional, remember this is running before validations), then any trailing /
is removed.
Those two URL strings will then be the same after tidying up, and thus the second time around the validation will kick in and stop it from being saved.
Hope that helps!
Upvotes: 2