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?
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?
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:
onchange
handler to the text fieldnew
an instance of your model, with the name or whatever set to the value Ajax sentslug
, and send the result back to the web pageAll 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.
FriendyId author here.
FriendlyId internally uses the private
set_slug
to do this. This method is invoked via abefore_validation
callback. If for some reason you do not wish to callvalid?
, you can invoke theset_slug
method viasend
, or define a method in your model which invokes it: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.