2013-03-21 50 views
0

我有一個用戶模型has_one配置文件。我在我的用戶模型下面的代碼:如何範圍從2個不同模型的結果?

class User < ActiveRecord::Base 
scope :city, lambda { |user| joins(:profile).where(:profiles => {:city => user.profile.city})} 
end 

然後在用戶控制器的我的索引行動:

def index 
    @users = User.city(current_user).paginate :page => params[:page], :per_page => 20 
    end 

這使我能夠從同一個城市的current_user獲取所有用戶。我還想做的是隻抓取那些上傳了個人資料圖片的用戶。我正在使用回形針,圖像列在Users表中。我想添加一些像show users where image_file_name != nil。但是上面的範圍包括配置文件表。我如何合併查詢以包含用戶表中的一列和配置文件表中的一列?

回答

3

您可以在Rails中連接作用域以形成最終查詢。

class User < ActiveRecord::Base 
    scope :city, lambda { |user| joins(:profile).where(:profiles => {:city => user.profile.city})} 
    scope :with_pictures, where('users.image_file_name IS NOT NULL') 
end 

假設這就是您的數據庫用來查找非空列的內容。

然後在你的控制器:

def index 
    @users = User.city(current_user).with_pictures.paginate :page => params[:page], :per_page => 20 
end 
+0

純粹的天才.... – pratski 2013-03-21 04:49:12