In my Activity model, I have a default scope:
default_scope where(:subject_id => Log.get_subject_id)
Problem is in Log.get_subject_id, default value is 0. Here is my Log model:
@@subject_id = 0
def self.set_subject_id(val)
@@subject_id = val
end
def self.get_subject_id
@@subject_id
end
When I change value of @@subject_id via Log.set_subject_id(10) in controller and then I try Activity.all, it always give me bad result. SQL:
SELECT "activities".* FROM "activities" WHERE "activities"."subject_id" = 0
Where is a problem? Thanks!
With that form of default_scope
, your Log.get_subject_id
call will be evaluated when the class is parsed so you're really saying something like this:
default_scope where(:subject_id => 0)
However, you can use a block with default_scope
to delay the evaluation of the scope until you try to use it and, presumably, Log.get_subject_id
will have a useful value:
default_scope { where(:subject_id => Log.get_subject_id) }