Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

activerecord find through association

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?

like image 683
Dimitris Avatar asked Jan 04 '11 14:01

Dimitris


2 Answers

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.

like image 114
Kevin Avatar answered Sep 19 '22 16:09

Kevin


The following piece of code did the trick:

User.joins(:account).joins('INNER JOIN "domains" ON "accounts"."id" = \
"domains"."account_id"').where(:users => {"username" => "Paul"}).
where(:domains => {"name" => "paul-domain"})

Sorry about the formatting of this long line of code

like image 25
Dimitris Avatar answered Sep 18 '22 16:09

Dimitris