开发者

Set DataMapper :order parameters from querystring params

开发者 https://www.devze.com 2023-02-18 22:36 出处:网络
As I\'m not yet fluent in Ruby, I\'m having struggling to construct an elegant solution for sorting in my Rails3/DataMapper project.

As I'm not yet fluent in Ruby, I'm having struggling to construct an elegant solution for sorting in my Rails3/DataMapper project.

The DataMapper examples show how to use symbols with asc or desc parameters to order restuls. For e开发者_JAVA技巧xample:

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

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

For lack of a better idea, this is what I have so far:

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 clunky. I'm certainly doing something wrong.


I've found another way to do this, but I'm not confident that this is the best way to go:

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


Alternatively, you could try doing something with send, like this:

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

I think your way is easier to understand though.

0

精彩评论

暂无评论...
验证码 换一张
取 消