ActiveRecord的发现通过协会 [英] activerecord find through association
问题描述
我尝试从我的分贝一个ActiveRecord对象。我的模型
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
和
class Account < ActiveRecord::Base
has_many :domains
has_many :users
end
和
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"}})
我知道,上面那块code将无法工作,因为我不得不提到一些有关的域的表。此外,用户和域之间的关联是一对多的(这可能进一步复杂的事情)。
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?
推荐答案
如果你使用的Rails 3.x中,以下code将得到查询结果:
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_sql
上面code。
To inspect what happen, you can append .to_sql
to above code.
如果你使用Rails的2.X,你最好写的原始的SQL查询。
If you're using Rails 2.x, you'd better write the raw sql query.
这篇关于ActiveRecord的发现通过协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!