0

Anyone have any idea what might be happening in this situation? Why is using self.class or scope resolution ::MyModel necessary?

class MyModel < ActiveRecord::Base

  belongs_to :other_model
  validate :custom_validation

  private
  def custom_validation
    if MyModel.where(some_field: 1).count > 0
      errors.add(:some_field, "foo")
    end
  end
end

# ... In some other part of the code base

my_model_instance = @other_model.my_models.find_or_initialize_by_some_field("foo")
my_model_instance.save
# Raises error - MyModel::MyModel is undefined

The above code works fine most of the time. But for some reason, in one situation it was throwing that exception. Changing the custom_validation function to use self.class instead of MyModel and it works.

  def custom_validation
    if self.class.where(some_field: "bar").count > 0
      errors.add(:some_field, "error message")
    end
  end

Has anyone seen anything like this before? Why/how can the constant MyModel be interpreted as MyModel::MyModel is this specific situation?

Ruby 2.0.0-p195 and Rails 3.2.13

edited: Clarify/add question about why scope resolution becomes necessary.

This question is pretty similar but it is still unclear to me why using MyModel without scope resolution works fine most of the time.

4

1 回答 1

5

You need to use the scope resolution operator so Ruby will not look for MyModel inside the MyModel namespace.

def custom_validation
  if ::MyModel.where(some_field: 1).count > 0
    errors.add(:some_field, "foo")
  end
end
于 2013-05-22T03:10:23.380 回答