activerecord find through association

谁说我不能喝 提交于 2019-12-19 03:16:24

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4594533/activerecord-find-through-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!