Set DataMapper: order parameters from querystring parameters

Since I don't own Ruby yet, I'm trying to build an elegant sorting solution in my Rails3 / DataMapper project.

The DataMapper examples show how to use characters with parameters ascor descto order restuls. For instance:

Document.all(:order => [:created_at.desc])

What will be the best way to convert params[:sort]and params[:direction]in an acceptable format for DataMapper?

Due to the lack of a better idea, this is what I still have:

sort_order = (params[:sort] || 'created_at').to_sym
sort_obj = params[:sort_dir] == 'desc' ? sort_order.desc : sort_order.asc
Document.all(:order => [sort_obj])

It works, but feels awkward. Of course, I have something wrong.

+3
source share
2 answers

I found another way to do this, but I'm not sure if this is the best way:

sort = DataMapper::Query::Operator.new(params[:sort], params[:sort_dir])
Document.all(:order => [sort])
+4
source

- send, :

Document.all(:order => [sort_order.send(params[:sort_dir] == "desc" ? :desc : :asc)])

, .

+1

All Articles