When is scope resolution necessary in Ruby (ActiveRecord) -


anyone have idea might happening in situation? why 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 other part of code base  my_model_instance = @other_model.my_models.find_or_initialize_by_some_field("foo") my_model_instance.save # raises error - mymodel::mymodel undefined 

the above code works fine of time. reason, in 1 situation throwing exception. changing custom_validation function use self.class instead of mymodel , works.

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

has seen before? why/how can constant mymodel interpreted mymodel::mymodel specific situation?

ruby 2.0.0-p195 , rails 3.2.13

edited: clarify/add question why scope resolution becomes necessary.

this question pretty similar still unclear me why using mymodel without scope resolution works fine most of time.

you need use scope resolution operator ruby not mymodel inside mymodel namespace.

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

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -