2014-01-11 171 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