add validation for name, used and quantity

This commit is contained in:
hitman 2017-03-21 16:46:09 +05:30 committed by Stella Rouzi
parent 4b72d383ea
commit e73baa2754
4 changed files with 25 additions and 4 deletions

View file

@ -578,6 +578,7 @@ module ApplicationHelper
end
def quantity_left_of(resource)
return '-/-' if resource.quantity.blank?
"#{resource.quantity - resource.used}/#{resource.quantity}"
end

View file

@ -1,10 +1,12 @@
class Resource < ActiveRecord::Base
belongs_to :conference
validate :used_less_than_quantity
validates :name, :used, :quantity, presence: true
validates :used, :quantity, numericality: { greater_than_or_equal_to: 0, only_integer: true }
validate :used_no_more_than_quantity
private
def used_less_than_quantity
errors.add(:used, 'can not be higher than total quantity') unless used <= quantity
def used_no_more_than_quantity
errors.add(:used, 'cannot be higher than total quantity') if used.present? && quantity.present? && used > quantity
end
end

View file

@ -9,7 +9,7 @@
.col-md-8
= semantic_form_for(@resource, :url => (@resource.new_record? ? admin_conference_resources_path : admin_conference_resource_path(@conference.short_title, @resource))) do |f|
= f.input :name
= f.input :description, input_html: { rows: 5, data: { provide: "markdown-editable" } }
= f.input :description, input_html: { rows: 5, data: { provide: 'markdown-editable' } }
= f.input :used
= f.input :quantity
%p.text-right

View file

@ -4,6 +4,24 @@ describe Resource do
let(:conference) { create(:conference) }
let(:resource) { create :resource }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_presence_of(:used) }
it { is_expected.to validate_presence_of(:quantity) }
it { is_expected.to validate_numericality_of(:used) }
it { is_expected.to validate_numericality_of(:quantity) }
it { is_expected.not_to allow_value(-1).for(:used) }
it { is_expected.to allow_value(0).for(:used) }
it { is_expected.not_to allow_value(-1).for(:quantity) }
it { is_expected.to allow_value(0).for(:quantity) }
it 'has a valid factory' do
expect(build(:resource)).to be_valid
end