简体   繁体   English

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

[英]Rails add two scope with active record result

I am using acts-as-taggable-on gem 我正在使用act-as-taggable-on gem

i use single field to search by tag_name and user_name 我使用单个字段按tag_name和user_name进行搜索

User.rb 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

But i have pagination issue while getting this as Array and i used "will_paginate/Array" in config/initializer/will_paginate.rb it doesn't work. 但我得到分页问题,​​而得到这个数组,我在config / initializer / will_paginate.rb中使用“will_paginate / Array”它不起作用。

User controller 用户控制器

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

Console. 安慰。

User.search("best") => Should search by both tag_name and user_name and return ActiveRecord result. User.search(“best”)=>应该同时搜索tag_name和user_name并返回ActiveRecord结果。

i want to get the result of User.search("best") union with result of tag name User.tagged_with("best") 我想得到User.search(“best”)union的结果与标签名称User.tagged_with(“best”)的结果

Can you help me to add this scopes as ActiveRecord relation to use pagination without issue. 你能帮我把这个范围作为ActiveRecord关系添加到使用分页而没有问题。

I think you just need to return a chainable scope (use . instead of + ): 我认为你只需要返回一个可链接的范围(使用.而不是+ ):

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

It returns an ActiveRecord::Relation instead of an Array . 它返回一个ActiveRecord::Relation而不是一个Array

If you need to perform an UNION operation, I recommend you to follow this thread: ActiveRecord Query Union . 如果您需要执行UNION操作,我建议您遵循以下线程: ActiveRecord Query Union

One possible approach is to extend ActiveRecord: 一种可能的方法是扩展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 

Usage (not tested): 用法(未测试):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM