# searching on a complex attribute in my model

**URL:** <https://discuss.rubyonrails.org/t/searching-on-a-complex-attribute-in-my-model/39616>\
**Category:** rubyonrails-talk\
**Created:** [February 20, 2009, 10:35pm UTC](https://discuss.rubyonrails.org/t/searching-on-a-complex-attribute-in-my-model/39616 "2009-02-20T22:35:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Frederick\_Cheung](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/frederick_cheung/32/3901_2.png) [@Frederick\_Cheung](https://discuss.rubyonrails.org/u/Frederick_Cheung)\
**Post date:** [February 20, 2009, 10:35pm UTC](https://discuss.rubyonrails.org/t/searching-on-a-complex-attribute-in-my-model/39616/1 "2009-02-20T22:35:19Z")

</div>

> Here is part of my User class:
> 
> has\_many :permissions has\_many :roles, :through =\> :permissions
> 
> This works very well, and I have a handy convenience method:
> 
> def has\_role?(name) self.roles.find\_by\_name(name) ? true : false end
> 
> However, I'm trying to figure out how to search the RoR way based on the role and some other criteria. For example, if I want to search for all users whose first name is Bob and have a role 'admin', what would I type in the conditions part of the query to filter by role? I know that with a User.find... query, I can no longer use the "self" keyword to call an instance method.

You going to have to use a join so that you can have conditions on both tables eg

User.find :all, :joins =\> :roles, :conditions =\> ["roles.name = ? AND users.name = ? ", 'admin', 'Bob']

Or you also do it less verbosely by reversing that: Role.find\_by\_name ('admin').users.find :all, :conditions =\> {:name =\> 'Bob'}

Fred

---

<div class="post-metadata">

**Author:** ![11175](https://avatars.discourse-cdn.com/v4/letter/1/8edcca/32.png) [@11175](https://discuss.rubyonrails.org/u/11175)\
**Post date:** [February 21, 2009, 12:31am UTC](https://discuss.rubyonrails.org/t/searching-on-a-complex-attribute-in-my-model/39616/2 "2009-02-21T00:31:35Z")

</div>

Thanks a lot!

Frederick Cheung wrote:
