Rails gem "friendly_id": How to get a live preview of the slug, before its object is created
friendly-id, live-preview, ruby-on-rails, rubygems, slug
Solution
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.
Problem
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?