0

我有一个用户模型该has_one配置文件。我的用户模型中有以下代码:

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. 我还想做的是只获取那些上传了个人资料图片的用户。我正在使用回形针,图像列在用户表中。我想添加类似show users where image_file_name != nil. 但是,上述范围包括配置文件表。如何合并查询以包含用户表中的一列和配置文件表中的一列?

4

1 回答 1

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
于 2013-03-21T04:45:14.587 回答