NoMethodError when trying to validate model field

L

laredotornado

Hi, When validating a field in my user model, I wrote a method
"is_client?" to help with the validation. But I did it wrong because
now I'm getting this error:

NoMethodError in SessionController#create
undefined method `is_client?' for User:Class
RAILS_ROOT: ./script/../config/..
Application Trace | Framework Trace | Full Trace
/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/
active_record/base.rb:1238:in `method_missing'
/usr/local/apache2/htdocs/easyrx/app/models/user.rb:16
/usr/local/apache2/htdocs/easyrx/app/controllers/session_controller.rb:
12:in `create'

Here's the relevant code. Any ideas what I can do to get rid of this
error? Thanks, - Dave

class User < ActiveRecord::Base
...
validates_as_phone :work_phone, :if => !:work_phone.blank? &&
is_client?, :message => "is not a valid phone number" # line
16

attr_accessible :user_type_id, :user_group_id, :pharmacy_id, :phone, :work_phone, :work_phone_extension, :fax, :bill_to_first_name, :bill_to_last_name, :bill_to_street, :bill_to_city, :bill_to_state, :bill_to_zip, :bill_to_country, :ship_to_first_name, :ship_to_last_name, :ship_to_street, :ship_to_city, :ship_to_state, :ship_to_zip, :ship_to_country, :bill_to_attn, :ship_to_attn, :bill_to_company, :ship_to_company, :bill_to_street2, :ship_to_street2, :login, :email, :password, :password_confirmation

....
def is_client?
user_type_id == 2
end

end
 
W

Wyatt Greene

I can explain why you're getting this error. validates_as_phone is a
method. All methods in Ruby have a receiver object. Because
validates_as_phone is called outside of a defined method, it's
receiver object is the User class itself, *not* an object of type
User. The arguments that you pass to the validates_as_phone method
include a call to the is_client? method. Since the receiver object is
the User class, it looks for a method called is_client? defined for
the User class, which would look like this:

def User.is_client?
user_type_id == 2
end

or another way to say the same thing is:

def self.is_client?
user_type_id == 2
end

Instead, it finds a method defined for User objects:

def is_client?
user_type_id == 2
end

Unfortunately, you can't just stick a self. onto your is_client?
method because user_type_id is a method that belongs to User objects,
not the User class itself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top