2013-01-06 27 views
0

我試圖用輪胎寶石做一個排序的搜索,但我總是得到這個錯誤:問題與輪胎和排序的搜索

解析失敗[無映射,以便發現[職業]作爲排序依據]

我的代碼有什麼問題? 以下是我的用戶型號

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 

回答

0

你能試試嗎?我想你在to_indexed_json中發送了職業名稱,而你正在嘗試對整個職業模型進行排序。

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