I have two different models with a 1:N relation.
Let’s name them ‘myobject’ and ‘related’
class Myobject < ActiveRecord::Base
has_many :related
scope :without_related, includes(:related).select{ |o| o.related.size == 0 }
end
class Related < ActiveRecord::Base
end
The defined scope seems to work great as long as I don’t create new assignments from Myobjects to Related:
- Direct rails c command “Myobject.includes(:related).select … (as defined in Scope) works as expected
- Calls to scope “Myobject.without_related” still return objects that have been assigned in the meantime
It seems that this can be fixed by restarting the rails console or restarting Webrick.
But I can’t always restart a webapplication only because a relation between objects has been changed 😉
Is there any way to fix this problem or to write the scope in a better way?
PS: I need this query as scope to pass its name as group_method to a grouped_select in the form of the Myobject model
I would recommend you to use counter_cache for this, you need to add column *related_count* of type int to Myobject, make migration and then you will be able to do so:
After that you will have super fast scope for getting all objects with no related records and an a count of that objects as well