Browse files

Using slug instead of key in Category

  • Loading branch information...
1 parent 04a1d27 commit 7f79c40b64346bf02bfccad7f299576e3f0e7fdc @jhbabon committed Apr 21, 2012
View
11 app/models/category.rb
@@ -1,15 +1,10 @@
# -*- encoding: utf-8 -*-
class Category < ActiveRecord::Base
+ extend FriendlyId
+ friendly_id :name, use: :slugged
+
validates :name, uniqueness: true, presence: true
attr_accessible :name
-
- # the key will helps in internal searchs and urls
- before_create :create_key
-
- def create_key
- self.key = self.name.parameterize
- end
- protected :create_key
end
View
7 db/migrate/20120421113622_rename_key_to_slug_in_categories.rb
@@ -0,0 +1,7 @@
+class RenameKeyToSlugInCategories < ActiveRecord::Migration
+ def change
+ rename_column :categories, :key, :slug
+ remove_index :categories, :key
+ add_index :categories, :slug
+ end
+end
View
6 db/schema.rb
@@ -11,16 +11,16 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20120421110715) do
+ActiveRecord::Schema.define(:version => 20120421113622) do
create_table "categories", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
- t.string "key"
+ t.string "slug"
end
- add_index "categories", ["key"], :name => "index_categories_on_key"
+ add_index "categories", ["slug"], :name => "index_categories_on_slug"
create_table "friendly_id_slugs", :force => true do |t|
t.string "slug", :null => false
View
7 db/seeds.rb
@@ -17,12 +17,12 @@ def seed_section(title)
def section(message)
$stdout.puts "\n"
- $stdout.puts "===== #{message}"
+ $stdout.puts "== #{message}"
$stdout.puts "\n"
end
def info(message)
- $stdout.puts "----- #{message}"
+ $stdout.puts "-- #{message}"
end
# seeds
@@ -42,7 +42,8 @@ def info(message)
seed_section 'Categories' do
%w(Música Cine).each do |name|
- if Category.find_by_key(name.parameterize)
+ info "Creating the category '#{name}'."
+ if Category.find_by_slug(name.parameterize)
info "The category '#{name}' exists. Skipping."
else
Category.create(name: name)
View
9 test/unit/category_test.rb
@@ -24,13 +24,4 @@ class CategoryTest < ActiveSupport::TestCase
assert @category.errors[:name].any?
end
- test "should set the key before create" do
- category = FactoryGirl.build(:category)
-
- assert category.key.blank?
- assert category.save
- assert category.key.present?
- assert_equal category.name.parameterize, category.key
- end
-
end

0 comments on commit 7f79c40

Please sign in to comment.