Sortable -table列在MongoDB中不起作用 [英] Sortable -table columns is not working in MongoDB

查看:107
本文介绍了Sortable -table列在MongoDB中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails投影片 http://railscasts.com/Episodes/240-search-sort-paginate-ajax . 它适用于Mysql数据库.我想在Mongodb中实现这一点. 我的application_helper.rb文件是这样的

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

我的products_controller.rb文件是这样的

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

我的product.rb模型是这样的

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

它在Mysql数据库中工作正常,但对于Mongodb,它会引发类似

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'

我搞砸了.我是Mongodb的新手.

I messed up. I am new to Mongodb.

推荐答案

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

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

这篇关于Sortable -table列在MongoDB中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆