Browse files

Add slugs to countries

  • Loading branch information...
1 parent f864316 commit a332e0d73dafb1becf1aed2d5d4b15c9cce581b7 @tomstuart tomstuart committed Feb 1, 2012
Showing with 41 additions and 1 deletion.
  1. +7 −0 app/models/country.rb
  2. +19 −0 db/migrate/20120201121512_add_slugs_to_countries.rb
  3. +4 −1 db/schema.rb
  4. +11 −0 test/unit/country_test.rb
View
7 app/models/country.rb
@@ -3,4 +3,11 @@ class Country < ActiveRecord::Base
has_many :documents, through: :document_countries
validates :name, presence: true
+
+ extend FriendlyId
+ friendly_id :name, use: :slugged
+
+ def should_generate_new_friendly_id?
+ new_record?
+ end
end
View
19 db/migrate/20120201121512_add_slugs_to_countries.rb
@@ -0,0 +1,19 @@
+class AddSlugsToCountries < ActiveRecord::Migration
+ Country.class_eval do
+ # temporarily generate slugs for existing objects
+ def should_generate_new_friendly_id?
+ super
+ end
+ end
+
+ def change
+ add_column :countries, :slug, :string
+ add_index :countries, :slug
+
+ Country.reset_column_information
+
+ Country.record_timestamps = false
+ Country.all.each(&:save)
+ Country.record_timestamps = true
+ end
+end
View
5 db/schema.rb
@@ -11,7 +11,7 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20120131093615) do
+ActiveRecord::Schema.define(:version => 20120201121512) do
create_table "attachments", :force => true do |t|
t.string "carrierwave_file"
@@ -41,8 +41,11 @@
t.text "embassy_address"
t.string "embassy_telephone"
t.string "embassy_email"
+ t.string "slug"
end
+ add_index "countries", ["slug"], :name => "index_countries_on_slug"
+
create_table "document_attachments", :force => true do |t|
t.integer "document_id"
t.integer "attachment_id"
View
11 test/unit/country_test.rb
@@ -10,4 +10,15 @@ class CountryTest < ActiveSupport::TestCase
country = build(:country, name: nil)
refute country.valid?
end
+
+ test 'should set a slug from the country name' do
+ country = create(:country, name: 'Costa Rica')
+ assert_equal 'costa-rica', country.slug
+ end
+
+ test 'should not change the slug when the country name is changed' do
+ country = create(:country, name: 'New Holland')
+ country.update_attributes(name: 'Australia')
+ assert_equal 'new-holland', country.slug
+ end
end

0 comments on commit a332e0d

Please sign in to comment.