arturaz / railserrorsfor
- Source
- Commits
- Network (0)
- Issues (0)
- Downloads (0)
- Wiki (1)
- Graphs
-
Branch:
master
README
ErrorMessagesFor
================
This plugin enchances the default rails functionality for the ActiveRecord helper 'error_messages_for'
What it does:
1. It allows you to enter an array of AR objects as the first argument and will display them all in the same output
block.
Example:
<%= error_messages_for [:user, :topic, :item] %>
With this bit of code you'll get something that looks like the following:
There were 3 errors that need to be fixed:
* User username can't be blank
* Topic title can't be blank
* Item body can't be blank
2. The second argument allows you to pass in a partial to render the errors. By default the first thing it looks for is
your partial, if that's nil, it'll look for the following partial:
RAILS_ROOT/app/views/application/_error_messages.rhtml If it doesn't find that it'll default to some inline text.
Example:
<%= error_messages_for :user, "my_errors" %>
You had 2 errors fool!
- User username can't be blank
- User email can't be blank
This is cool if you want to change the way errors are displayed in a pop-up vs. your main site, or you want to change
them on a whole section of the site, etc...
3. A method is added to all of your AR objects called, 'business_name'. By default this method will return the class of
the AR object.
Example:
user.business_name returns "User"
item.business_name returns "Item"
This is used when generating the error messages. Here's the way a message is rendered: "business_name column_name
error_message". So the following model:
class Item < ActiveRecord::Base
validates_presence_of :body, :message => "can't be blank."
end
would produce the following error message:
"Item body can't be blank."
The business_name method allows you to override the first part of the error message if your business speak doesn't match
your database speak. An example would be if your business wants to call Items, Articles. In that case you would do the
following:
class Item < ActiveRecord::Base
validates_presence_of :body, :message => "can't be blank."
def business_name
"Article"
end
end
would produce the following error message:
"Article body can't be blank."
Pretty sweet, eh?
4. The last thing you can do is override the entire message from start to finish. Let's say, using the last example,
that the business doesn't like the message, "Article body can't be blank.", instead they want the message to be, "Oi,
give us a body!!". That's easy. All you have to do is start your :message attribute with a "^".
Example:
class Item < ActiveRecord::Base
validates_presence_of :body, :message => "^Oi, give us a body!!"
end
would produce the following error message:
"Oi, give us a body!!"
This plugin offers you great flexibility, and probably should've been done right from the start in Rails core. Hope it
helps.
