Skip to content

Instantly share code, notes, and snippets.

@wrightling
Last active December 17, 2015 00:18
Show Gist options
  • Save wrightling/5519521 to your computer and use it in GitHub Desktop.
Save wrightling/5519521 to your computer and use it in GitHub Desktop.
JSON error thoughts
class Card < ActiveRecord::Base
attr_accessible :reference, :scripture, :subject
validates :scripture, presence: true, length: { minimum: 20 }
validate :at_least_one_subject_or_reference
def self.updated_since(time)
if time
Card.where("updated_at >= ?", time)
else
Card.all
end
end
private
def at_least_one_subject_or_reference
if String(subject).empty? && String(reference).empty?
errors[:handle] << "Please include a reference or subject"
end
end
end
>> c = Card.new
=> #<Card id: nil, subject: nil, scripture: nil, reference: nil, created_at: nil, updated_at: nil>
>> c.save
(0.4ms) BEGIN
(0.5ms) ROLLBACK
=> false
>> c.errors.as_json
=> {:scripture=>["can't be blank", "is too short (minimum is 20 characters)"], :handle=>["Please include a reference or subject"]}
{"errors": { "scripture": ["can't be blank","is too short (minimum is 20 characters)"],"handle":["Please include a reference or subject"]}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment