activerecord find through association

Dimitris picture Dimitris · Jan 4, 2011 · Viewed 20.5k times · Source

I am trying to retrieve an activerecord object from my db. My models are

class User < ActiveRecord::Base
   belongs_to :account
   has_many :domains, :through => :account    
end

And

class Account < ActiveRecord::Base
   has_many :domains
   has_many :users
end

And

class Domain < ActiveRecord::Base
   belongs_to :account
end

Now I would like to retrieve a user based on the username and a domain name (lets assume that these are attributes of the User and the Domain classes respectively). i.e. something along the lines of

User.find(:first, :conditions =>{:username => "Paul", :domains => { :name => "pauls-domain"}})

I know that the above piece of code will not work since I do have to mention something about the domains table. Also, the association between users and domains is a one-to-many (which probably further complicates things).

Any ideas on how should this query be formed?

Answer

Kevin picture Kevin · Jan 4, 2011

If you're using Rails 3.x, the following code would get the query result:

User.where(:username => "Paul").includes(:domains).where("domains.name" => "paul-domain").limit(1)

To inspect what happen, you can append .to_sql to above code.

If you're using Rails 2.x, you'd better write the raw sql query.