Friday, March 28, 2014

Rails Default Scope Affects Model Initialization

Hi Guys - Ran into this while working on a project.  Now, default scope works fine for most of the stuff but it also has a secret to itself which I didn't realize (my bad).

Lets consider two cases,  one in which default scope affect is realized and other one in which it isn't.

------------
class ModelNotAffected < ActiveRecord::Base
  attr_accessible :name, :is_deleted

  default_scope where(:is_deleted => 0)
end

------------

class ModelAffected < ActiveRecord::Base
  attr_accessible :stall, :is_active

  default_scope where(:is_active => 1)
end

------------

How ?

ModelNotAffected.new({:name => 'Spider Man'})
# => {:name => 'Spider Man', :is_deleted => 0}
# This is what u kind of want

ModelAffected.new({:stall => Art Works''})
# => {:stall => 'Art Works', :is_active => 1}
# This might not be the case. There might be some condition which would make the stall as is_active

Well note that how default scope affects model initialization.

Thanks

No comments:

Post a Comment