NoMethodError when trying to validate model field

Discussion in 'Ruby' started by laredotornado, Jan 28, 2008.

  1. 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
    active_record/base.rb:1238:in `method_missing'
    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

    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

    laredotornado, Jan 28, 2008
    1. Advertisements

  2. laredotornado

    Wyatt Greene Guest

    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

    or another way to say the same thing is:

    def self.is_client?
    user_type_id == 2

    Instead, it finds a method defined for User objects:

    def is_client?
    user_type_id == 2

    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.
    Wyatt Greene, Jan 29, 2008
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.