# Named\_scope and habtm chaining problem

**URL:** <https://www.ruby-forum.com/t/named-scope-and-habtm-chaining-problem/143605>\
**Category:** Rails\
**Created:** [July 21, 2008, 5:30am UTC](https://www.ruby-forum.com/t/named-scope-and-habtm-chaining-problem/143605 "2008-07-21T05:30:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Danimal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/bb73d2/32.png) [@Danimal](https://www.ruby-forum.com/u/Danimal)\
**Post date:** [July 21, 2008, 5:30am UTC](https://www.ruby-forum.com/t/named-scope-and-habtm-chaining-problem/143605/1 "2008-07-21T05:30:01Z")

</div>

Can anyone help me with this?

I have a habtm relationship. I defined a named\_scope on one side of  
it. It works fine except when I chain it. For example:

```auto
class Category < ActiveRecord::Base
  has_and_belongs_to_many :items
end

class Item < ActiveRecord::Base
  has_and_belongs_to_many :categories

  named_scope :cat, lambda {|cat| {:include
=> :categories, :conditions => ["categories.id = ?", cat]}}
end
```

Simple. Easy. Normal, right?

## But, let’s see I have the following in my join table “categories\_items”: category\_id | item\_id

```
 1 1
 1 2
 2 2
 2 3

```

So I try some console stuff (I’m taking out the object return and just  
showing the IDs)

> Item.cat(1) # =\> [1,2]  
> Item.cat(2) # =\> [2,3]  
> Item.cat(1).cat(2) # =\> []

WAIT! Shouldn’t that return [2] ?

Is this a bug? Or am I misunderstanding something?

If I force the “AND” it works:

> Item.cat(1) & Item.cat(2) # =\> [2]

So the chaining of named scopes seems not to be working here.

Help?!?

-Danimal
