Hi all
I have the following custom validation helper in application.rb:
module ActiveRecord::Validations::ClassMethods
def validates_email_format_of(*attr_names)
configuration = {}
configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
validates_each(attr_names.first.to_s) do |record, attr_name, value|
unless configuration[:if] and not
evaluate_condition(configuration[:if], record) # Evaluate :if option
next if configuration[:allow_nil] and
record.send("#{attr_name}_before_type_cast").nil? # Skip this one if
emptyness is allowed and the email attribute is empty
if record.send(attr_name.to_sym) !~
/^([a-z0-9.-äöüèà éê_])+@([a-z0-9.-äöüèà éê_])+.([a-z]{2,})$/i #
Check if the email is valid
record.errors.add(attr_name,
ActiveRecord::Errors::default_error_messages[:invalid_email_format])
end
end
end
end
end
In my model Member I call validates_email_format_of :email.
class Member < ActiveRecord::Base
…
validates_email_format_of :email
…
end
When starting script/console there’s no problem - When no email or a
wrong email is supplied, I get the appropriate error message added to
the model instance.
However, when adding the following migration…
class AddCreatorAndOwner < ActiveRecord::Migration
def self.up
# Check if there is a member with the ID 1 which is supposed to be
the webmaster
raise “There is no member with the ID 1 (Webmaster)!” unless
Member.find(1)
# Add the new column :creator_id which holds as default the ID 1
(webmaster)
add_column :music_artists, :creator_id, :integer, :null => false,
:default => 1, :references => :members, :on_delete => :restrict
# Alter the field so for future management of music artists one has
to specify a creator_id (1 is not default anymore!)
execute(“ALTER TABLE music_artists MODIFY creator_id INTEGER(11) NOT
NULL”)
end
def self.down
drop_column :music_artists, :creator_id
end
end
…I always get the following error:
192:~/Sites/projects/export josh$ rake db:migrate
/usr/local/bin/rake:17:Warning: require_gem is obsolete. Use gem
instead.
(in /Users/josh/Sites/projects/export)
== AddCreatorAndOwner: migrating
rake aborted!
undefined method `validates_email_format_of’ for Member:Class
(See full trace by running task with --trace)
What’s wrong here? Why won’t the Member class find the
validates_email_format_of method in the migration, but when using it in
the console it does?
Thanks a lot for help.
Josh