簡體   English   中英

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

[英]Sortable -table columns is not working in MongoDB

我正在使用rails cast視頻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的新手。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM