Forum: Ruby on Rails searching on a complex attribute in my model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E43eedb17c626f5b9a4ad3b93cd51ef9?d=identicon&s=25 Naija Guy (naijaguy)
on 2009-02-20 23:03
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.

Thanks for any help...
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-02-20 23:36
(Received via mailing list)
On Feb 20, 10:03 pm, Naija Guy <rails-mailing-l...@andreas-s.net>
wrote:
>
> 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
E43eedb17c626f5b9a4ad3b93cd51ef9?d=identicon&s=25 Naija Guy (naijaguy)
on 2009-02-21 01:31
Thanks a lot!


Frederick Cheung wrote:
> On Feb 20, 10:03�pm, Naija Guy <rails-mailing-l...@andreas-s.net>
> wrote:
>>
>> 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
This topic is locked and can not be replied to.