# Has\_many :through and named\_scope

**URL:** <https://www.ruby-forum.com/t/has-many-through-and-named-scope/186459>\
**Category:** Rails\
**Created:** [April 7, 2010, 1:38pm UTC](https://www.ruby-forum.com/t/has-many-through-and-named-scope/186459 "2010-04-07T13:38:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tom-mac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/bc8723/32.png) [@tom-mac](https://www.ruby-forum.com/u/tom-mac)\
**Post date:** [April 7, 2010, 1:38pm UTC](https://www.ruby-forum.com/t/has-many-through-and-named-scope/186459/1 "2010-04-07T13:38:09Z")

</div>

Hi  
I have the models roles, users and user\_roles. The relationship among  
them is

## user.r

user has\_many user\_roles  
user has\_many roles, :through =\> :user\_roles

# role.rb

role has\_many user\_roles  
role has\_many users, :through =\> :user\_roles

# user\_role.rb

belongs\_to :user  
belongs\_to :role

```
 Suppose a login user1 has roles [admin, staff] And login user2 has

```

only one role say [participant] Now how can I check the cases

1)a login user is an admin or staff  
2) a login user has\_role participant?

```
  And also I would like to know whether this can be written using

```

named scopes.(I am totally new to named scopes)

Thanks in advance  
Tom

---

<div class="post-metadata">

**Author:** ![tom-mac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/bc8723/32.png) [@tom-mac](https://www.ruby-forum.com/u/tom-mac)\
**Post date:** [April 7, 2010, 3:41pm UTC](https://www.ruby-forum.com/t/has-many-through-and-named-scope/186459/2 "2010-04-07T15:41:55Z")

</div>

user1.roles returns an array of roles.  
The array class has a function “include?(obj)” that returns true or  
false.

Something like this should work:  
user1.roles.include?(Role.find\_by\_name(‘admin’))

Named scopes are not ment for stuff like this.  
You can create a function on the user model “is\_admin?” for the code  
above. That way if how an admin is defined changes, you only need to  
update the code in one place.

---

<div class="post-metadata">

**Author:** ![tom-mac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/bc8723/32.png) [@tom-mac](https://www.ruby-forum.com/u/tom-mac)\
**Post date:** [April 7, 2010, 3:50pm UTC](https://www.ruby-forum.com/t/has-many-through-and-named-scope/186459/3 "2010-04-07T15:50:06Z")

</div>

Better off saying !roles.find\_by\_name(“admin”).blank?  
Saves on SQL

Blog: [http://random8.zenunit.com/](http://random8.zenunit.com/)  
Twitter: [http://twitter.com/random8r](http://twitter.com/random8r)  
Learn: [http://sensei.zenunit.com/](http://sensei.zenunit.com/)  
New video up now at [http://sensei.zenunit.com/](http://sensei.zenunit.com/) real fastcgi rails  
deploy process! Check it out now!
