可排序的列 - 表中没有工作的MongoDB(Sortable -table columns is

2019-10-17 13:35发布

我使用的铸铁护栏视频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。

Answer 1:

Mongoid本身并不支持COLUMN_NAMES方法。 什么,你需要做的是供应一个自己,这添加到您的模型。

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


文章来源: Sortable -table columns is not working in MongoDB