ruby on rails -轮胎和排序搜索的问题



我试图做一个排序搜索使用轮胎宝石,但我总是得到这个错误:

解析失败[找不到[occupation]的映射,无法对其进行排序]]

我的代码有什么问题?以下是我的用户模型

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  include Tire::Model::Search
  include Tire::Model::Callbacks
  belongs_to :occupation
  field :name, :type => String, :default => ""
  field :email, :type => String, :default => ""
  field :kind, :type => String, :default => ""
  def to_indexed_json
    { id: id,
      name: name,
      email: email,
      kind: kind,
      occupation: occupation.try(:name),
      created_at: created_at,
      updated_at: updated_at
    }.to_json
  end
  mapping do
    indexes :id, :type => 'integer'
    indexes :name, :type => 'String'
    indexes :email, :type => 'String'
    indexes :kind, :type => 'String'
    indexes :occupation, :type => 'String'
    indexes :created_at, :type => 'Date'
    indexes :updated_at, :type => 'Date'
  end
  def self.search q, params={}
    tire.search page: (params[:page] || 1)  do |search|
      search.query do |query|
        query.string q
      end
      search.sort do |sort|
        sort_column = params[:sort] || 'occupation'
        sort_direction = params[:direction] || 'asc'
        sort.by(sort_column.to_sym, sort_direction)
      end
    end
  end
end

你能试试吗?我猜你是在to_indexed_json中发送occupation.name,你正试图对整个职业模型进行排序。

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  include Tire::Model::Search
  include Tire::Model::Callbacks
  belongs_to :occupation
  field :name, :type => String, :default => ""
  field :email, :type => String, :default => ""
  field :kind, :type => String, :default => ""
  def to_indexed_json
    { id: id,
      name: name,
      email: email,
      kind: kind,
      occupation: occupation.try(:name),
      created_at: created_at,
      updated_at: updated_at
    }.to_json
  end
  mapping do
    indexes :id, :type => 'integer'
    indexes :name, :type => 'String'
    indexes :email, :type => 'String'
    indexes :kind, :type => 'String'
    indexes :occupation, :type => 'object' do
        indexes :name, :type => 'String'
    end
    indexes :created_at, :type => 'Date'
    indexes :updated_at, :type => 'Date'
  end
  def self.search q, params={}
    tire.search page: (params[:page] || 1)  do |search|
      search.query do |query|
        query.string q
      end
      search.sort do |sort|
        sort_column = params[:sort] || 'occupation.name'
        sort_direction = params[:direction] || 'asc'
        sort.by(sort_column, sort_direction)
      end
    end
  end
end

最新更新