activerecord find through association

前端 未结 2 1238
悲&欢浪女
悲&欢浪女 2021-01-06 00:15

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

class User < ActiveRecord::Base
   belongs_to :account
   has_many :domains, :thr         


        
相关标签:
2条回答
  • 2021-01-06 00:27

    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

    0 讨论(0)
  • 2021-01-06 00:45

    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.

    0 讨论(0)
提交回复
热议问题