Take the 2-minute tour ×

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
    direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
    link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}

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)



  def sort_column
    Product.column_names.include?(params[:sort]) ? params[:sort] : "name"

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"

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) 

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.

share|improve this question
Looks like you didn't define a class method named column_names inside your Product model? –  scaryguy Dec 30 '12 at 12:19
I have edited my question with Product model also. where do i have to define this? can u edit my question.. –  regmiprem Dec 30 '12 at 12:22
MongoDb is document driven, not columns. What would column names map to in a structured document? –  WiredPrairie Dec 30 '12 at 12:36
can u edit my question for my result. I am new to Mongodb. Hope u will –  regmiprem Dec 30 '12 at 12:38
def self.column_names #here comes your code for this particular method end –  scaryguy Dec 30 '12 at 15:14

1 Answer 1

up vote 4 down vote accepted

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] }
share|improve this answer
Thanks dude you save my ass from my boss!!!!!!!!!!! –  regmiprem Dec 31 '12 at 8:56
like a boss. ;-) –  gmaliar Dec 31 '12 at 10:34

Your Answer


