2013-03-21 51 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