Rails gem "friendly_id": How to get a live preview of the slug, before its object is created

1.1k views Asked by At

Using the Rails gem "friendly_id", is it possible to get a "live preview" of the slug to be created? Before the object is saved, that is (and to be returned while typing using an ajax request)?

If so, how?

2

There are 2 answers

0
Norman Clarke On BEST ANSWER

FriendyId author here.

FriendlyId internally uses the private set_slug to do this. This method is invoked via a before_validation callback. If for some reason you do not wish to call valid?, you can invoke the set_slug method via send, or define a method in your model which invokes it:

instance = ModelClass.new
instance.send(:set_slug)

# or
class ModelClass < ActiveRecord::Base
  friendly_id :name, use: :slugged

  def generate_slug_preview
    set_slug
  end
end 

However, note that bypassing or ignoring validations is often a bad idea. For example, if your model included a validation on the name field, and then you used that field as the basis of the slug, then you are previewing a slug that will never actually be generated.

5
Phlip On

Per https://github.com/norman/friendly_id/blob/master/test/slugged_test.rb ...

  m1 = model_class.new :name => "a b c d"
  m1.valid?
  assert_equal "a-b-c-d", m1.slug

Looks like it's just .slug. Per other tests, you don't need the create - a new will do. So your strategy is:

  • add an onchange handler to the text field
  • each time the user changes it, use Ajax to send the current value to the server
  • new an instance of your model, with the name or whatever set to the value Ajax sent
  • call slug, and send the result back to the web page
  • display it in the web page

All that is standard Ajax stuff, with nothing to do with friendly_id. But it all makes me wonder if - because you show the slug to the user - friendly_id will let you then edit the slug, the way high-end blogs do.

And you probably must call valid? first.