Sortable -table columns is not working in MongoDB

蹲街弑〆低调 提交于 2019-12-11 10:37:47

问题


I am using rails cast video http://railscasts.com/episodes/240-search-sort-paginate-with-ajax . It works fine for Mysql database. i want to implement this in Mongodb. my application_helper.rb file is like this

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

my products_controller.rb file is like this

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

My product.rb model is like this

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

It works fine in Mysql database but for Mongodb it throws error like

undefined method `column_names' for Product:Class
app/controllers/products_controller.rb:81:in `sort_column'
app/controllers/products_controller.rb:6:in `index'

I messed up. I am new to Mongodb.


回答1:


Mongoid doesn't support a column_names method by itself. What you need to do is supply one yourself, add this to your model.

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


来源:https://stackoverflow.com/questions/14090621/sortable-table-columns-is-not-working-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!