public

  • Download Gist
form_builder_extensions.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Chuck this in config/initializers for view-first validations
ActionView::Base.default_form_builder.class_eval do
def error(field)
errors(field).first
end
def errors(field)
object.errors.for(field)
end
end
 
ActiveRecord::Errors.class_eval do
def generate_message(attribute, message = :invalid, options = {})
message
end
 
def for(attribute)
case err = self.on(attribute)
when String, Symbol: [err]
when Array: err
when NilClass: []
end
end
end
register.haml
Haml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
-# And you can use it in a view like so:
 
- form_for :user, @user, register_path do |f|
%fieldset
!= f.label :name
!= f.text_field :name
- if f.error(:name) === :blank
.error.name_blank= _("You don't have a name??")
!= f.label :email
!= f.text_field :email
- case f.error(:email)
- when :blank
.error.email_blank= _("You don't have an email??")
- when :invalid
.error.email_format= _("That doesn't look like an email address!")
- when :taken
.error.email_taken
_("There is an account already registered with that email address.")
%a{:href => root_path(:email => @user.email)} _("Log in instead?")
- when :foo
.error.foo= _("You need to foo first")
user.rb
Ruby
1 2 3 4 5 6
class User < ActiveRecord::Base
validates_presence_of :email, :name, :password,
validates_format_of :email, :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i, :allow_blank => true
validates_uniqueness_of :email, :case_sensitive => false
my_custom_validates_of :email, :message => :foo
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.