2014-01-11 180 views
1
得到一个单一查询所选元素

我有(Rails中3.2.13):如何使用连接到两个表

class User < ActiveRecord::Base 
    has_many :app_event_login_logouts 
end 

class AppEventLoginLogout < ActiveRecord::Base 
    belongs_to :user 
end 

,并想拿回类似:

AppEventLoginLogoug.select("id, type, users.email").joins(:user) 

基本上是id,键入来自app_event_login_logouts和用户的电子邮件,但这似乎不起作用。什么是正确的语法?

回答

1

试试下面的代码:

ret = User.joins(:app_event_login_logouts).select('app_event_login_logouts.id, app_event_login_logouts.type, users.email') 
ret.first.id # will return app_event_login_logouts.id 
ret.first.email # will return users.email 
... 
+0

THX,为什么不反向的工作?像AppEventLoginLogout.joins(:用户)? – timpone

+0

没有区别。你尝试过吗?在我机器的工作。试试这个如果不是'AppEventLoginLogout.joins(:user).select('app_event_login_logouts.id,app_event_login_logouts.type,users.email')' –

+1

thx,那有效。我以为我试过了这个组合。需要一些咖啡;-) – timpone

1
AppEventLoginLogoug.find(:all, 
         {:include => [:users], 
          :select => ['id', 'type', 'users.email']}) 

我还检查apidoc,发现类似的东西:

result= AppEventLoginLogoug.find(:all, 
           :conditions => ['condition_here'], 
           :joins => [:users], 
           :select => 'whatever_to_select' 
           :order => 'your.order') 
+0

我认为这将工作:'@ logins_logouts = AppEventLoginLogout.select([“id”,“user_id,created_at,users.email”])。includes(:user)' – timpone

+0

我编辑了代码,请再检查一次 – bkdir