Nested with_scope and :joins


I've been trying to DRY up my models in my current Rails project by
adding a dash of the very useful with_scope. However, I quickly
realized that when nesting with_scopes the outermost :joins are
forgotten. This somewhat limits the extent to which I can exploit the
use of with_scope.

Is there any way to preserve :joins through a nested with_scope stack?

Also, I've noticed that when extending a has_many :through association
with a find(:all, :joins => ...) the :through SQL join is forgotten
and causes a SQL syntax error. I think that this may be related to the
with_scope :joins problem.

Perhaps someone can shed some light on the reasoning behind this



Danger, danger! with_scope considered harmful. with_scope is not a generic, do-it-all SQL combiner. It was only implemented to allow chaining foreign keys conditions between associations:

invoice.lineitems.find(1) == Lineitem.with_scope(:find => { :conditions => [‘invoice_id = ?’, invoice_id] }) { Lineitem.find(1) }

Please combine your conditions and joins explicitly if possible.