I would like my User model to deactivate some data before saving. At the moment, the simplest white spaces. Therefore, to avoid registering people with Harry and, for example, pretend to be Harry.
I suggest that it is a good idea to do this deletion before validation, so that validates_uniqueness_of can avoid accidental duplicates.
class User < ActiveRecord::Base has_many :open_ids validates_presence_of :name validates_presence_of :email validates_uniqueness_of :name validates_uniqueness_of :email validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[az]{2,})\Z/i before_validation :strip_whitespace, :only => [:name, :email, :nick] private def strip_whitespace(value) value.responds_to?('strip') ? value.strip : value end end
However, this code contains an ArgumentError error: the wrong number of arguments (0 for 1). I assumed that the callback would be passed values.
Also: is stripping really a good idea? Or I should rather settle in space and tell the user that “Harry” contains an invalid space (I want to allow “Harry Potter”, but not “Harry \ s \ sPotter”).
Edit: As stated in the comment, my code is incorrect (that is why I asked ao question). Please make sure that you read the accepted answer in addition to my question about the correct code and avoid the same mistakes that I made.
validation ruby-on-rails model
berkes Jul 16 '10 at 19:05 2010-07-16 19:05
source share