I have the table Slug with the field url which is unique.
If I create @slug = Slug.url = "foo"
When I go to save, if Slug.url of "foo" already exists, I would like to then try for a Slug.url of "foo-1" if that also exists, try "foo-2" foo-3, foo-4, etc. until a value is found that doesn't exist and can be created in the database. What would be the right way to go about this in my Rails model?
My latest code looks like this:
def set_url
self.url = self.title.parameterize
# Ensure the url is available
qUrl = self.url.split('-').shift
slugs = Slug.where("url like '#{qUrl}%'")
if slugs.exists?
c = slugs.count + 1
self.url = self.url + "-" + c.to_s
end
end
The problem with this code is the qUrl is picking up false positives, any time a title starts with the word "why" slugs are being found. Is there an approach that is more reliable and elegant?
I'd suggest using the friendly_id gem for this. If you look at the documentation in the slugged object, you'll see that it has a mechanism to handle uniqueness by appending a uuid to the slug name.
Alternatively, there are a number of other slug generating gems that might work better for your environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With