THpubs
THpubs

Reputation: 8172

In Rails friendly_id how to use multiple attributes for the slug?

I need to generate the slug with multiple attributes. For example, I need the title and the id both in every record (Not only in the ones with duplicate titles). So it will look like this : hello-world-8943. How can I do this?

Upvotes: 2

Views: 880

Answers (3)

Andrey Deineko
Andrey Deineko

Reputation: 52357

Accoriding to docs, you can define your own slug structure as follows:

class MyModel < ActiveRecord::Base

  friendly_id :uniqueslug, use: :slugged

  def uniqueslug
    "#{title}-#{id}"
  end

end

Upvotes: 3

Mini John
Mini John

Reputation: 7941

You just have to pass your own slug:

That for example generates a random string.

  extend FriendlyId
  friendly_id :random_slug, use: [:slugged, :finders]

  def random_slug
    self.slug = SecureRandom.hex(5)
  end

Upvotes: 0

Nermin
Nermin

Reputation: 6100

Put in your model

def to_param
   "#{title.parameterize}-#{id}"
end

Upvotes: 0

Related Questions