Skip to content

Commit

Permalink
Add basic validations for Product slugs
Browse files Browse the repository at this point in the history
Problem:

On the demo site, it's rather simple for users to craft product names
that don't translate into valid slugs.

When Rails tries to render links to these products, it throws a 500
error because it cannot generate a correct URL.

Solution:

Add validators to ensure that all products have a valid and unique slug.
  • Loading branch information
c-lliope committed Nov 6, 2015
1 parent a61c16f commit 0a92fca
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
8 changes: 8 additions & 0 deletions spec/example_app/app/models/product.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ class Product < ActiveRecord::Base
validates :image_url, presence: true
validates :name, presence: true
validates :price, presence: true
validates :slug, uniqueness: true
validate :valid_slug

def to_s
name
Expand All @@ -16,4 +18,10 @@ def name=(value)
def to_param
slug
end

def valid_slug
if slug.blank?
errors.add :name, "must have letters or numbers for the URL"
end
end
end
15 changes: 15 additions & 0 deletions spec/models/product_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,20 @@
it { should validate_presence_of(:image_url) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:price) }

it "should not allow names that produce empty slugs" do
product = build(:product, name: "???")

product.validate

expect(product.errors[:name]).
to include("must have letters or numbers for the URL")
end

context "with other products in the database" do
subject { build(:product) }

it { should validate_uniqueness_of(:slug) }
end
end
end

0 comments on commit 0a92fca

Please sign in to comment.