Rails adds two areas with an active write result

I am using action-as-taggable-on gem

I use one field to search by tag name and username

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 a pagination problem, when I get it as Array and I used "will_paginate / Array" in config / initializer / will_paginate.rb, this does not work.

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") => Must search for both username and username tags and return an ActiveRecord result.

I want to get the result of combining User.search ("best") with the result of the tag name User.tagged_with ("best")

Can you help me add these scopes as an ActiveRecord relationship to using pagination without a problem.

+4
1

, ( . +):

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

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
+3

Source: https://habr.com/ru/post/1612586/


All Articles