Rails 添加两个具有活动记录结果的范围

Rails add two scope with active record result

我正在使用 acts-as-taggable-on gem

我使用单个字段按 tag_name 和 user_name

进行搜索

User.rb

class User < ActiveRecord::Base

  acts_as_taggable
  attr_accessor: :user_name, :age, :country, tag_list
  scope :tagged_with, lambda { |tag|
    {
      :joins => "INNER JOIN taggings ON taggings.taggable_id = user.id\
               INNER JOIN tags ON tags.id = taggings.tag_id AND taggings.taggable_type = 'User'",
      :conditions => ["tags.name = ?", tag],
      :order => 'id ASC'
    }
  }
  def self.search(search)
    if search
      where('name LIKE ?', "%#{search}%") + tagged_with(search)
    else
      scoped
    end
  end
end

但是我在将它作为数组获取时遇到了分页问题,​​我在 config/initializer/will_paginate.rb 中使用了 "will_paginate/Array" 它不起作用。

用户控制器

class UserController < ActionController::Base
  def index
    @users = User.search(params[:search]).paginate(:per_page => per_page, :page => params[:page])
  end

控制台。

User.search("best") => Should search by both tag_name and user_name and return ActiveRecord result.

我想获得 User.search("best") 与标记名称 User.tagged_with("best")

联合的结果

你能帮我把这个作用域添加为 ActiveRecord 关系,以便毫无问题地使用分页吗?

我认为你只需要 return 一个可链接的范围(使用 . 而不是 +):

where('name LIKE ?', "%#{search}%").tagged_with(search)

它 return 是 ActiveRecord::Relation 而不是 Array

如果您需要执行 UNION 操作,我建议您关注此线程:ActiveRecord Query Union

一种可能的方法是扩展 ActiveRecord:

module ActiveRecord::UnionScope
  def self.included(base)
    base.send(:extend, ClassMethods)
  end

  module ClassMethods
    def union_scope(*scopes)
      id_column = "#{table_name}.id"
      sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(" UNION ")
      where("#{id_column} IN (#{sub_query})")
    end
  end
end 

用法(未测试):

class User < ActiveRecord::Base
  include ActiveRecord::UnionScope

  def self.search(search)
    if search
      union_scope(where('name LIKE ?', "%#{search}%"), tagged_with(search))
    else
      scoped
    end
  end
end