2014-01-11 21 views
1

我有2個模型 - User和User_detail。如何在.joins查詢中使用模型範圍

表:

User 
|id| 

User_detail 
|id|user_id|active| 

的UserDetails型號:

class UserDetails < ActiveRecord::Base 
    belongs_to :user 

    scope :active, -> { where("active is null or active = true") } 
end 

如何使用這個範圍在查詢中只得到活躍用戶?

事情是這樣的:

User.joins(:user_details).active 

回答

0

這應該工作:

User.joins(:user_details).merge(UserDetails.active) 

退房http://asciicasts.com/episodes/215-advanced-queries-in-rails-3更多的ActiveRecord的技巧!

+0

這看起來像它的產生2個獨立的查詢:'用戶負載(爲0.8ms)SELECT用戶* FROM用戶INNER JOIN user_details ON user_details.user_id = users.id UserDetails加載(0.4ms)SELECT user_details。* FROM user_details WHERE(active爲null或active = true)' – Catfish

+0

它看起來像'&'快捷鍵已被刪除。合併仍然有效! –