Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friendly_id: slug_candidates not naming slug properly

I have the following in my model:

class Dispenser < ActiveRecord::Base

  extend FriendlyId

  friendly_id :slug_candidates, use: :slugged

  def slug_candidates
    [
      :full_name,
      [:full_name, :id]
    ]
  end

end

This is generating slugs like:

=> 'bob-barker-bob-barker-15'

Really it should be bob-barker or bob-barker-15, but not both.

https://github.com/norman/friendly_id

like image 216
Abram Avatar asked Dec 01 '13 08:12

Abram


3 Answers

FriendlyId author here. As mentioned earlier, you need FriendlyId 5 for this, it won't work with 4.0.

Also note that you can not use the id field as a part of the slug, because the slug is generated before the record is created.

If you are willing to have the id field in the slug, then there are easier solutions available other than FriendlyId, such as overriding the to_param method as described here.

like image 96
Norman Clarke Avatar answered Nov 03 '22 06:11

Norman Clarke


[:full_name, :id] - you can do this only onUpdate (when :id already set) When you are creating a new record in your DB table this will not work!

For you purpose you should use some like this

def slug_candidates
[
  :name,
  [:name, 2],
  [:name, 3],
  [:name, 4],
  [:name, 5],
  [:name, 6],
  [:name, 7],
]

end

Or shortly

def slug_candidates
  [:name] + Array.new(6) {|index| [:name, index+2]}
end

It's simple way to solve this problem without extra SQL query

like image 4
Dima Melnik Avatar answered Nov 03 '22 07:11

Dima Melnik


The functionality you're describing is in version 5

See: https://github.com/norman/friendly_id#what-changed-in-version-50

What you've written is essentially just returning an array of symbols which is running through the parameterize method after it's cast to a string ...

2.0.0p247 :002 > ['name',['name',15]].to_s.parameterize # this is what friendly_id does in the background
 => "name-name-15"

Hope that helps

like image 3
Matenia Rossides Avatar answered Nov 03 '22 05:11

Matenia Rossides