0

I have already setup Friendly Id following all the instructions from the Home page.

In short,i have added the module and slug column in my Place model table.

in my place.rb

  extend FriendlyId
  friendly_id :name, use: [:slugged, :finders, :history]

I also ran Place.find_each(&:save).

Now the value of name can be different,as there are many places with same names.So in the index action when i call the show action,using id,i get correct results but urls looks bad,However,when i call show action using friendly_id,url is bad here too with its uniq token like string attached and also i always get wrong result.

for example. For a record with name value as burwood,there can be multiple entries too.However,there are two problems:-

  1. My urls should be like www.mysite/sydney/burwood instead of www.mysite/sydney/21,if i am using id and not friendly_id(which looks weird - www.mysite/sydney/burwood-78894aa3-dea1-4915-b2f7-038182511005),How to handle this. ??
  2. If i dont use Id and use friendly_id as url parameter,For similar locations of value burwood,i am always get first record even if i am asking for other one.So in DB, name value of burwood having two records,my slug values are different - burwood and burwood-78894aa3-dea1-4915-b2f7-038182511005

So if use id as url parameter,it works as id's are uniq and slugs are not considered but i want url to be more meaningful.

However,if i use friendly_id,url looks weird and also unique record is not picked up.

Kindly help

NM Pennypacker
  • 6,704
  • 11
  • 36
  • 38
Milind
  • 4,535
  • 2
  • 26
  • 58

1 Answers1

2

If there are many places with the same name, then friendly_id will append a guid to the end of the slug to make it unique.

You can try using friend_id candidates:

From the docs:

A new "candidates" functionality which makes it easy to set up a list of alternate slugs that can be used to uniquely distinguish records, rather than appending a sequence. For example:

class Restaurant < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  # Try building a slug based on the following fields in
  # increasing order of specificity.
  def slug_candidates
    [
      :name,
      [:name, :city],
      [:name, :street, :city],
      [:name, :street_number, :street, :city]
    ]
  end
end

https://github.com/norman/friendly_id

Alternatively you can roll your own slug by overriding to_param in the Place model and using a before_validation filter to set the slug.

before_validation :format_slug

def to_param
  slug
end

private

def format_slug
  self.slug = "#{name} #{id}".parameterize
  # You can define any rules for your slug here.
end

And if you want the params[:id] to read params[:slug] in the controller instead, then set param: :slug in your routes.

resources :places, param: :slug

And in your controllers:

Place.find_by(slug: params[:slug])
codyeatworld
  • 1,263
  • 7
  • 9