0

Using Rails 2.3.4, Ruby 1.8.7.

I have an ActiveRecord validation where I want to include the user's input in the error message. The simplified version of I'm doing something like this:

record.errors.add attr, "'#{calculated_value}' is not valid.'

Where calculated_value is a portion of the user's input of a larger value.

I've found that if the user enters values that contain certain characters, odd things can happen. If calculated_value contains %s, %s gets replaced by the full value the user entered. If calculated_value contains .., I got:

ArgumentError - interning empty string from /var/lib/gems/1.8/gems/activesupport-2.3.4/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb:196:in `to_sym'.

I would like to know how I can disable the functionality or how I can escape these values. I tried escaping %s to %%s, sprintf-style, but that doesn't work.

zishe
  • 10,665
  • 12
  • 64
  • 103
jb_314
  • 1,373
  • 2
  • 17
  • 28

1 Answers1

0

I dunno whether this method was available in rals 2.3.4. But can you try out activerecord Inclusion. This helper validates that the attributes’ values are included in a given set. So your code will be something like

class YourModel< ActiveRecord::Base
  validates :calculated_value, :inclusion => { :in => %w(Valid Values you want),
    :message => "%{calculated_value} is not a valid value" }
end
AnkitG
  • 6,438
  • 7
  • 44
  • 72
  • My validation is more complicated than a list of acceptable values. It's not that I have a problem with the logic to determine an incorrect value, it's that the string I give to record.errors.add gets rewritten if it contains certain sequences of characters, like %s. – jb_314 Sep 10 '12 at 23:45
  • @np_ can u site example of the scenario what exactly is happening – AnkitG Sep 11 '12 at 17:25