ruby-on-rails – Rails添加两个具有活动记录结果的范围
我正在使用act-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”)union的结果与标签名称User.tagged_with(“best”)的结果 你能帮我把这个范围作为ActiveRecord关系添加到使用分页而没有问题. 解决方法
我认为你只需要返回一个可链接的范围(使用.而不是):
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |