Customizing Error Messages In RAILS

In every application regardless of its complexity we require to customize error messages to make more sense. There are several ways to achieve it in Rails 3 and in Rails 2.3.x which are mentioned specifically and that can be handled either in models or controllers or helpers.

Solution# 1:

If it is needed to be handled in model and message need to be have customized instead of the attribute name. Like if the attribute name is “name” but you want to display messages “Employee name cannot be blank” then we have to install “custom-err-msg” plug-in.

This plugin gives you the option to not have your custom validation error message prefixed with the attribute name. Ordinarily, if you have, say:

validates_acceptance_of : terms, :message => 'Please accept the terms of service'

You’ll get the following error message: Terms Please accept the terms of service

This plugin allows you to omit the attribute name for specific messages. All you have to do is begin the message with a ‘^’ character. Example:

validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'

step# 1

To install the ”custom-err-msg” plug-in you have to use the command.

“ruby script/plugin install https://github.com/gumayunov/custom-err-msg.git”

If you are facing problem by installing the plugin then clone it and just copy the folder (”gumayunov-custom-err-msg-640db42”) inside “Vendor/plugin/” folder

step# 2

In view file just display it as mentioned below:

Similarly, it can use in other places like,

validates_presence_of :claim_no, :message => "^Work Order/Claim number cannot be blank!"

The plugin also lets you use procs instead of strings.

Example:

validates_acceptance_of :accepted_terms, :message => Proc.new {|service| "You must accept the terms of the service #{service.name}" }

The above plug-in usage can be avoided by declaring alias for each attribute as mentioned below.
You should have a file named config/locales/en.yml, if not simply create one. There you can add your own custom names.

en:
activerecord:
models:
order: "Order"
attributes:
order:
b_name: "Business Name"

This will replace your attribute “b_name” with “Business Name”

Your Order model in app/models/order.rb should look like:

class Order < ActiveRecord::Base
validates :b_name, :presence => true

The error message will be displayed like

Business Name cannot be blank

Solution# 3:

Another way is to define a method and an error message inside the method in the model.

Class Employee < ActiveRecord::Base
validate :zip_must_be_valid
def zip_must_be_valid
unless zip.map(&:valid?).all?
errors.add_to_base " zip code is invalid"
end
end
end

We can also customize the error messages in Controllers.
Suppose “First Name” cannot be blank to be checked. Then use below code to check for it and show customized messages

if(params[:employee][:first_name].nil?)
flash[:error] = "First name should not be blank.n"
end

Subsequently, if it is required to add other messages to the above for other attributes then it can be written as,

if(params[:employee][:address].nil?)
flash[:error] += Address should not be blank.n"
end

Solution# 5

Customization of error messages can be done in controllers by adding messages to the existing error object’s method “add_to_base”.

if email_data[:"email_no_#{i}"] != "" && email_data[:"email_no_#{i}"] !~ /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i
valid_params = false
@company_info_new.errors.add_to_base( "Invalid Email Id!" )
End

In views it can be displayed by writing below code:

0 %>
nil, :message => nil >

Solution# 6

The customization that can be handled in views using

“error_message_on” helpers (Rails 2.3.8)”

In case you wish to show one error message in a specific location that relates to a specific validation then use “error_message_on” helper. You might have used “error_message_on” to display field-specific error messages. Here is an example that would display an error message on a name field:

Solution# 7

You can also use “error_message_on”(Rails 2.3.8) to display non-field-specific error messages.

class User < ActiveRecord:Base
validate :user_is_active
private
def user_is_active
if self.is_active != true
errors.add : user_is_active, 'User must be active to continue'
end
end
end

Now, to display this custom validation error message with “error_message_on”, we simply need to reference “:user_is_active” when we call the helper. Consider this implementation:

Solutions# 8

class User < ActiveRecord::Base validates_presence_of :email validates_uniqueness_of :email validates_format_of :email, :with => /^[wd]+$/ :on => :create, :message => "is invalid"
end

In Rails 3 it’s possible to call a validate method and pass it a hash of attributes to define the validations instead of defining each validation separately as mentioned above.
/app/models/user.rb

class User < ActiveRecord::Base validates :email, :presence => true,
:uniqueness => true,
:format => { :with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i }
end

In the User model we’re still validating that the field has a value and that the value is unique. For validating the format there are a number of options we can pass so we use a secondary hash to define those.

We can supply any number of validations for an attribute with a single command. While this is useful it can become cumbersome if there are a large number of validations but for most situations, it works nicely.

We can make the “:format” option more concise and clean it up a little. We often want to validate email addresses and having the same long regular expression in each validator is a little ugly and introduces repetition into the code. We can extract this out into a separate validation by creating a new class in our application’s /lib directory. We’ll call the file email_format_validator.rb.

class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end

The EmailFormatValidator class inherits from ActiveModel:: EachValidator. We have to define one method in the class “validate_each”, that takes three parameters called object, attribute and value. The method then checks that the value matches the regular expression we’re using to validate an email address and if not it will add the attribute to the objects errors.

We can use this technique to define any kind of validation we like. Now that we have our custom validator we can update the validator in the “User” model to use it.
/app/models/user.rb

class User < ActiveRecord::Base
validates :email,
:presence => true,
:uniqueness => true,
:format => { :with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i }
end

Having an email_format key in the “validates” hash means that the validator will look for a class called email_format_validator and passes the validation behavior into the custom class that we just wrote.
If we try to create a new user now and enter an invalid email address we’ll see the expected error message.

If you have some trick to share, do it in the comments.

Apple iPhone 5 And iPad-Mini: Rumors Or Truth

Lately there are rumors about the iPhone 5 is being under development to have a year end release. If the rumors are true then it will surely bring an excitement among iPhone application development industries.

With marginal improvement to iPhone 4, Apple launched the iPhone 4S in 2011 with voice recognition system Siri and a cloud storage service iCloud. Based on the iOS 5.1.1, iPhone 4S acts as hotspot by sharing its internet connection over Wi-Fi, Bluetooth or USB and also users can access the App Store.

A reports say that a Taiwan based manufacturer is assigned with the development of iPhone 5 and the manufacturing process is under way. As per the rumors, the new iPhone will have the back of both glass and aluminum. The most debated features that the iPhone 5 may have are: 7.9 mm thickness, Retinal display, near field communication technology, Passbook feature from iOS and a quad core process in hardware configuration.

Never miss an update from us. Join 10,000+ marketers and leaders.

Above all these there is also a possibility that iPhone 5 will come with a 19 pin dock connector instead of the current 30 pin connector, to include the headset jack aside. If this happens all the old dock connectors available with current versions will be useless.

Apart from iPhone 5, there are also rumors about an iPad Mini(a smaller version of iPad) will be launched in near future. As per anonymous resources its been claimed that the new iPad Mini will have a screen size of smaller than 8 inches compared to 9.7 inches of iPad. The third generation tablet iPad3 has major features like high resolution Retinal display, 5 MP iSight camera. And it will come with iLife and iWork apps.

If Apple is taking majors to develop iPad Mini or any similar product, hopefully most of these features or some better features will be incorporated into it. As per reports the iPad Mini will be launched during Christmas season of this year. But again there is no official announcement from Apple about these rumors. If iPad Mini is under development then it will surely give tough competition to Google’s recently released tablet Nexus 7.

I’ve worked with the team at Andolasoft on multiple websites. They are professional, responsive, & easy to work with. I’ve had great experiences & would recommend their services to anyone.

Ruthie Miller, Sr. Mktg. Specialist

Salesforce, Houston, Texas

LEARN MORE

Most of the mobile application development companies are waiting to see whether these rumors will be true in the near future and ready to develop apps with the help of latest technologies. Andolasoft adapts a differential approach to become a leading iPhone application development company to fulfill business requirements and serve individuals by developing rather multitasking but simpler iPhone apps.

Here at Andolasoft we follow cutting edge technologies to develop easy-to-use apps to increase business efficiency and productivity. We’ve experienced iPhone application developers who work closely with you in an agile and innovative environment. We have expertise to develop apps those are intuitive and easy-to-use.

The Horizons of CakePHP Application Development

CakePHP is an open-source web development framework for PHP. It came into prominence around 2006 and it was inspired by the Ruby on Rails framework, which was introduced around a year prior to it.

CakePHP follows MVC pattern architecture. Like RoR, it also follows the two key design features, DRY or “Don’t Repeat Yourself” and CoC or “Convention over Configuration”.

CakePHP development is a rapid development framework with thoughtful, coherent design and is well aided by friendly community contributions. It relies on a ORM (Object-Relation Model) regarding database query interface.

Never miss an update from us. Join 10,000+ marketers and leaders.

Using CakePHP’s ORM, we can create, retrieve, update and delete related data into and from different database tables with simplicity and in a better way. There is no need to write complex SQL queries anymore.

Some of the key features of CakePHP are:

  • Flexible Licensing
  • Compatibility with PHP4 and PHP5
  • Integrated CRUD for database interaction and simplified queries
  • Application Scaffolding
  • Request dispatcher with good looking, custom URLs
  • Built-in Validation
  • Fast and flexible templating (PHP syntax, with helpers)
  • View Helpers for AJAX, JavaScript, HTML Forms and more
  • Security, Session, and Request Handling Components
  • Flexible access control lists
  • Data Sanitization
  • Flexible View Caching

Andolasoft Inc. offers quick and cost effective CakePHP development to built robust and scalable web applications for start-up and established business houses, institutions etc.