可排序的表列在MongoDB中不起作用

时间:2012-12-30 12:14:37

标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid

我正在使用rails cast video http://railscasts.com/episodes/240-search-sort-paginate-with-ajax。 它适用于Mysql数据库。我想在Mongodb中实现这一点。 我的application_helper.rb文件是这样的

def sortable(column, title = nil)
    title ||= column.titleize
    css_class = column == sort_column ? "current #{sort_direction}" : nil
    direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
    link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
  end

我的products_controller.rb文件就像这样

helper_method :sort_column, :sort_direction
  def index
   @products = Product.search(params[:search]).order_by(sort_column + " " + sort_direction)


  end


private

  def sort_column
    Product.column_names.include?(params[:sort]) ? params[:sort] : "name"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end

我的product.rb模型是这样的

class Product
  include Mongoid::Document
  include Mongoid::Timestamps
  field :name, type: String
  field :price, type: String
  field :released_at, type: String

  def self.search(search)
    if search
       where(name: /#{Regexp.escape(search)}/i) 
     else
       scoped
    end
  end
end

它在Mysql数据库中工作正常,但对于Mongodb,它会抛出错误,如

undefined method `column_names' for Product:Class
app/controllers/products_controller.rb:81:in `sort_column'
app/controllers/products_controller.rb:6:in `index'
我搞砸了。我是Mongodb的新手。

1 个答案:

答案 0 :(得分:3)

Mongoid本身不支持column_names方法。 您需要做的是自己提供一个,将其添加到您的模型中。

  def self.column_names
    self.fields.collect { |field| field[0] }
  end