Permalink
Browse files

Added key to Category

  • Loading branch information...
1 parent f4fd8f3 commit 5b5068ebb8b06ecb0cdb570eabd4fd6142a62476 @jhbabon committed Apr 20, 2012
View
@@ -1,5 +1,15 @@
+# -*- encoding: utf-8 -*-
+
class Category < ActiveRecord::Base
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
@@ -0,0 +1,6 @@
+class AddKeyToCategories < ActiveRecord::Migration
+ def change
+ add_column :categories, :key, :string
+ add_index :categories, :key
+ end
+end
View
@@ -11,14 +11,17 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20120416214952) do
+ActiveRecord::Schema.define(:version => 20120420184536) 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"
end
+ add_index "categories", ["key"], :name => "index_categories_on_key"
+
create_table "images", :force => true do |t|
t.string "title"
t.string "resource"
View
@@ -1,3 +1,5 @@
+# -*- encoding: utf-8 -*-
+
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
@@ -38,8 +40,13 @@ def info(message)
end
end
-
-# TODO: this should be improved as previously seen
-Category.delete_all
-Category.create(name: "Música")
-Category.create(name: "Cine")
+seed_section 'Categories' do
+ %w(Música Cine).each do |name|
+ if Category.find_by_key(name.parameterize)
+ info "The category '#{name}' exists. Skipping."
+ else
+ Category.create(name: name)
+ info "Category '#{name}' created."
+ end
+ end
+end
@@ -2,6 +2,6 @@
FactoryGirl.define do
factory :category do
- name { Faker::Lorem.words 1 }
+ name { Faker::Lorem.sentence 1 }
end
end
View
@@ -1,17 +1,20 @@
+# -*- encoding: utf-8 -*-
+
require 'test_helper'
class CategoryTest < ActiveSupport::TestCase
setup { @category = FactoryGirl.create(:category) }
+ teardown { Category.delete_all }
test "name should be unique" do
category_a = FactoryGirl.build(:category, name: "category a")
category_a_bis = FactoryGirl.build(:category, name: "category a")
- category_a.save
+ assert category_a.save
assert category_a.valid?
- category_a_bis.save
+ assert !category_a_bis.save
assert category_a_bis.invalid?
end
@@ -20,5 +23,14 @@ class CategoryTest < ActiveSupport::TestCase
assert @category.invalid?
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 5b5068e

Please sign in to comment.