Chaining two named_scope that have a block of code

Hi,

I have a named_scope that retrieves all the products for the current
website based on its domain name:

named_scope :site, lambda { |website_name| { :joins => :site,
:order => ‘products.created_at DESC’,
:conditions => [‘sites.domain_name = ?’, website_name]}}

Then I would like to chain another named_scope to the previous one, so
that it adds one more condition to the query:

named_scope :single, lambda { |permalink| { :conditions => [‘permalink =
?’, permalink], :limit => 1 } }

Then in my controller I invoke:

@product = Product.site(website_name).single(params[:permalink])

And here is the SQL generated:

SELECT count(*) AS count_all FROM products INNER JOIN sites ON
sites.id = products.site_id WHERE ((products.permalink =
‘demarrer-la-virtualisation-avec-xen’) AND (sites.domain_name =
‘digiprof.eu’)) LIMIT 1

I don’t know how in hell this count(*) made its way in the SQL!? Is this
a bug from named_scope? Everything works fine if there is only 1
named_scope in the chain that has a block of code.

I solved it by appending the first method to the chain.

I have another problem:

I want to chain 2 named_scopes that both have a :joins in their
definition. The problem is that the :joins of the second named_scope in
the chain doesn’t get added to the query. IS that normal behavior?

Fernando P. wrote:

I solved it by appending the first method to the chain.

I have another problem:

I want to chain 2 named_scopes that both have a :joins in their
definition. The problem is that the :joins of the second named_scope in
the chain doesn’t get added to the query. IS that normal behavior?

I solved that problem too, it was again the select(*) that was getting
in the way.

Now another question: can I chain 2 named_scopes that define the :joins
option? Is named_scope smart enough to append the two :joins like it
does for :conditions? I can’t make it happen. Only one of the :joins
finds its way in the final query sent to the DB.

Actually chaining 2 named_scopes that have :joins in them is not yet
possible as of Rails 2.1.1, the issue is fixed and is available in Rails
edge, or we’ll have to wait until 2.2 is out.