diff --git a/lib/friendly_id/finder_methods.rb b/lib/friendly_id/finder_methods.rb index f24921aa5..cf6de804e 100644 --- a/lib/friendly_id/finder_methods.rb +++ b/lib/friendly_id/finder_methods.rb @@ -47,7 +47,7 @@ def potential_primary_key?(id) when :integer Integer(id, 10) rescue false when :uuid - id.match /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ + id.match /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ else true end diff --git a/test/schema.rb b/test/schema.rb index cbf2a0e6a..2c4dc5cd3 100644 --- a/test/schema.rb +++ b/test/schema.rb @@ -23,10 +23,10 @@ def up end end - tables_with_string_primary_key.each do |table_name| - create_table table_name, primary_key: :string_key, id: false do |t| + tables_with_uuid_primary_key.each do |table_name| + create_table table_name, primary_key: :uuid_key, id: false do |t| t.string :name - t.string :string_key, null: false + t.string :uuid_key, null: false t.string :slug end add_index table_name, :slug, unique: true @@ -73,7 +73,7 @@ def slugged_tables %w[journalists articles novelists novels manuals] end - def tables_with_string_primary_key + def tables_with_uuid_primary_key ["menu_items"] end diff --git a/test/slugged_test.rb b/test/slugged_test.rb index 7d15b112c..c0429e819 100644 --- a/test/slugged_test.rb +++ b/test/slugged_test.rb @@ -241,7 +241,7 @@ class Journalist < ActiveRecord::Base end end -class StringAsPrimaryKeyFindTest < MiniTest::Unit::TestCase +class UuidAsPrimaryKeyFindTest < MiniTest::Unit::TestCase include FriendlyId::Test class MenuItem < ActiveRecord::Base @@ -250,12 +250,17 @@ class MenuItem < ActiveRecord::Base before_create :init_primary_key def self.primary_key - "string_key" + "uuid_key" + end + + # Overwrite the method added by FriendlyId + def self.primary_key_type + :uuid end private def init_primary_key - self.string_key = SecureRandom.uuid + self.uuid_key = SecureRandom.uuid end end @@ -263,16 +268,25 @@ def model_class MenuItem end - test "should have a string as a primary key" do - assert_equal model_class.primary_key, "string_key" - assert_equal model_class.columns.find(&:primary).name, "string_key" + test "should have a uuid_key as a primary key" do + assert_equal model_class.primary_key, "uuid_key" + assert_equal model_class.columns.find(&:primary).name, "uuid_key" + assert_equal model_class.primary_key_type, :uuid end - test "should be findable by the string primary key" do + test "should be findable by the UUID primary key" do with_instance_of(model_class) do |record| assert model_class.friendly.find record.id end end + + test "should handle a string that simply contains a UUID correctly" do + with_instance_of(model_class) do |record| + assert_raises(ActiveRecord::RecordNotFound) do + model_class.friendly.find "test-#{SecureRandom.uuid}" + end + end + end end class UnderscoreAsSequenceSeparatorRegressionTest < MiniTest::Unit::TestCase