Question: I have a `Site` model with `name` and `slug` parameters. I would like the rails app to generate the slug every time the user saves the `Site`, but want the `slug` to be unique. I have a validation to ensure uniqueness.

The challenge I have is that when a user creates a second site with the same name, an identical slug is generated. eg `name = "Hello` and `name = "hElLo"` both generate `hello`

```
  before_validation :create_slug

  private

  def create_slug
    self.slug =  self.name.parameterize
  end

```

I tried adding a while loop that checked whether a site with the same slug existed and added "-1" to the slug each loop until it was unique. The problem is that if I updated a site, the loop would see that a site with the same slug existed, and increment the slug, but the site that already exists was the same site.

Here's the code I was using:

```
  def create_slug
    a = self.name.parameterize
    while Site.where(slug:a).count > 0 do
      a = a + "-1"
    end
    self.slug = a
  end

```

Answer: 
I think you can solve your problem in two steps.

First avoid checking the slug always by modifying your before\_filter to a conditional one

```
before_validation :create_slug if: :name_changed?

```

that way, the callback will be executed only when the `name` field is updated.

Second modify the `name` validator so that it will check for exactly what you need instead of using the default uniqueness validator provided by rails, or move the validation to the `slug` field.
This might not be the answer you are looking for, but a good strategy would be to put the date in the permalink, so it would be something like

`/post/:year/:month/:day/:slug`

This would help to avoid the url duplication