0

Say I have a uniqueness constraint on name inside its has_many association. This would mean I don't need the ugly numeric sequence added to conflicting slugs.

As an example 2 slugs might get the same name in a game db from 2 different people having a game called 'cards' /person/1/games/cards and person/2/games/cards these are 2 different URLs but the slug on the second will look like person/2/game/cards2bc08962-b3dd-4f29-b2e6-244710c86106. person has a name uniqueness constraint on the name of their games so they cant have 2 games called 'cards' which stops 2 of the same slug being generated.

Problem is that the name of the games are all sorted in the one db so the conflicting slugs will have the numeric sequence added when its not needed, so urls become unnecessarily ugly.

Hope that made sense as to why I want it.

Anyway. How can I stop the numeric sequence from being added to conflicting slugs?

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
Rob
  • 1,835
  • 2
  • 25
  • 53

2 Answers2

4

Use the scoped functionality

class Card
   friendly_id :name, :use => :scoped, :scope => [:person]
end
j-dexx
  • 10,286
  • 3
  • 23
  • 36
2

To add to the accepted answer, there is also the slug_candidates method:

#app/models/card.rb
class Card < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  def slug_candidates
    [
      :name,
      [:name, :person_id]
    ]
  end
end

The above will create:

#url.com/players/1/games/cards
#url.com/players/2/games/cards-2

Whilst not as good as scoped for what you need, it will give you some options with other implementations.

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • Literally just realised I need something like this as well for another model and you game me the answer before I had to look it up. Also I saw this in the github docs looking for my answer to the question but skimmed over it thinking it was for some other purpose. – Rob Feb 15 '16 at 10:47
  • 1
    You should also make sure you look up about the [`history`](http://www.rubydoc.info/github/norman/friendly_id/FriendlyId/History) module for `friendly_id`. It's a separate db which stores all the historic slugs; most skip it but it's required for using `scope` – Richard Peck Feb 15 '16 at 10:49
  • 1
    Thanks! I've been stuck on another question for a couple days now, can you give it a quick look over? If you don't know just leave it. http://stackoverflow.com/questions/35378426/rails-cant-get-errors-to-display-on-a-failed-ajax-form-submit – Rob Feb 15 '16 at 10:50