# Change association methods behaviour

**URL:** <https://www.ruby-forum.com/t/change-association-methods-behaviour/139055>\
**Category:** Rails\
**Created:** [May 30, 2008, 2:49pm UTC](https://www.ruby-forum.com/t/change-association-methods-behaviour/139055 "2008-05-30T14:49:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dante\_R](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/f475e1/32.png) [@Dante\_R](https://www.ruby-forum.com/u/Dante_R)\
**Post date:** [May 30, 2008, 2:49pm UTC](https://www.ruby-forum.com/t/change-association-methods-behaviour/139055/1 "2008-05-30T14:49:31Z")

</div>

Hello there,

I am building an application where users are distributed among different  
user groups (User has\_many UserGroup). But there is a specific type of  
User  
(admin) that I would like to belong to ALL groups. I know I can add them  
to  
the group on the after\_create or after\_update method of UserGroup, but I  
would like to do something different.

My question is:

Is it possible that user.user\_groups return all groups if the user is an  
admin, and the normal group list if he is not? Admin is a boolean field  
of  
User.

if you need more info, please let me know.

best,  
Dante

---

<div class="post-metadata">

**Author:** ![Dante\_R](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/f475e1/32.png) [@Dante\_R](https://www.ruby-forum.com/u/Dante_R)\
**Post date:** [May 30, 2008, 3:10pm UTC](https://www.ruby-forum.com/t/change-association-methods-behaviour/139055/2 "2008-05-30T15:10:41Z")

</div>

finder\_sql may be a way to do this, something like:

has\_many :user\_groups, :finder\_sql =\> “SELECT DISTINCT user\_groups.\*  
FROM user\_groups #{'WHERE user\_groups.user\_id = ’ + id unless admin}”

---

<div class="post-metadata">

**Author:** ![Dante\_R](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/f475e1/32.png) [@Dante\_R](https://www.ruby-forum.com/u/Dante_R)\
**Post date:** [May 30, 2008, 6:01pm UTC](https://www.ruby-forum.com/t/change-association-methods-behaviour/139055/3 "2008-05-30T18:01:46Z")

</div>

On 30 May 2008, at 14:10, Thorsten M. wrote:

> finder\_sql may be a way to do this, something like:
> 
> has\_many :user\_groups, :finder\_sql =\> “SELECT DISTINCT user\_groups.\*  
> FROM user\_groups #{'WHERE user\_groups.user\_id = ’ + id unless admin}”

although that will have to be =\> ‘…’ so that this is interpolated at  
the right point in time

Fred
