diff --git a/lib/friendly_id/slugged.rb b/lib/friendly_id/slugged.rb index ab0fc2f2b..36f34c924 100644 --- a/lib/friendly_id/slugged.rb +++ b/lib/friendly_id/slugged.rb @@ -86,7 +86,7 @@ def self.down class Person < ActiveRecord::Base extend FriendlyId friendly_id :name_and_location, use: :slugged - + def name_and_location "#{name} from #{location}" end @@ -248,6 +248,7 @@ def self.included(model_class) defaults[:sequence_separator] ||= '-' end model_class.before_validation :set_slug + model_class.after_validation :unset_slug_if_invalid end # Process the given value to make it suitable for use as a slug. @@ -324,6 +325,14 @@ def slug_generator end private :slug_generator + def unset_slug_if_invalid + if errors.present? && attribute_changed?(friendly_id_config.query_field) + diff = changes[friendly_id_config.query_field] + self.slug = diff.first + end + end + private :unset_slug_if_invalid + # This module adds the `:slug_column`, and `:sequence_separator`, and # `:slug_generator_class` configuration options to # {FriendlyId::Configuration FriendlyId::Configuration}. diff --git a/test/slugged_test.rb b/test/slugged_test.rb index b0d334af7..531baafa7 100644 --- a/test/slugged_test.rb +++ b/test/slugged_test.rb @@ -92,6 +92,47 @@ def should_generate_new_friendly_id? end end + test "should not set slug on create if unrelated validations fail" do + klass = Class.new model_class do + validates_presence_of :active + friendly_id :name, :use => :slugged + + def self.name + "Journalist" + end + end + + transaction do + instance = klass.new :name => 'foo' + refute instance.save + refute instance.valid? + assert_nil instance.slug + end + end + + test "should not update slug on save if unrelated validations fail" do + klass = Class.new model_class do + validates_presence_of :active + friendly_id :name, :use => :slugged + + def self.name + "Journalist" + end + end + + transaction do + instance = klass.new :name => 'foo', :active => true + assert instance.save + assert instance.valid? + instance.name = 'foobar' + instance.slug = nil + instance.active = nil + refute instance.save + refute instance.valid? + assert_equal 'foo', instance.slug + end + end + end class SlugGeneratorTest < TestCaseClass