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