Tuesday, May 3, 2011

How do I tell Rails that a string is an Acronym?

I have a field called sui in one of my models. It stands for "Standard User Identifier." When there are validation errors on the field, Rails prints "Sui is required" or "Sui is already taken."

How can I tell Rails that 'sui'.titleize is "SUI"? I looked at Inflector.human, but that isn't quite right.

From stackoverflow
  • In such cases I use custom_err_msg plugin. As it is installed you can give custom error messages like this:

    validates_presence_of :sui, :message => '^SUI is required'
    

    When you put ^ at the begining then Rails don't put field name.

    EDIT: There is another plugin i18n_label used for translations, but with it you can in very simple way replace a name of your field with something nicer (on plugin page there is an example). It will substitute name in:

    <%= f.label :sui %>
    YourModel.human_attribute_name "sui"
    

    and in error messages.

    James A. Rosen : FANTASTIC tip! Is there a way to put the value that's causing problems into the message? "#{sui} is taken" won't work since it gets eval'd at the wrong time.
    James A. Rosen : I'm hoping someone has a suggestion that works for more than just error messages, but I do like the plugin.

0 comments:

Post a Comment