繁体   English   中英

Rails:用params排序查询?

[英]Rails: Sorting a query by params?

我正在使用运行一个简单的查找全部并使用willpaginate进行分页,但我也希望将查询按用户排序。 想到的第一个解决方案就是使用params [:sort]

http://localhost:3000/posts/?sort=created_at+DESC

@posts = Post.paginate :page => params[:page], :order => params[:sort]

但他的方法的问题是查询默认为按ID排序,我希望它是created_at。

这是一种安全的排序方法,有没有办法默认为created_at?

我使用命名范围来提供默认顺序(自Rails 2.1起可用)。

您将在Post模型中添加范围:

named_scope :ordered, lambda {|*args| {:order => (args.first || 'created_at DESC')} }

然后你可以打电话:

@posts = Post.ordered.paginate :page => params[:page]

上面的示例将使用named_scopecreated_at DESC )中的默认顺序,但您也可以提供另一个:

@posts = Post.ordered('title ASC').paginate :page => params[:page]

你可以在Romulo的建议中使用它:

sort_params = { "by_date" => "created_at", "by_name" => "name" }
@posts = Post.ordered(sort_params[params[:sort]]).paginate :page => params[:page]

如果在sort_params找不到params[:sort]并返回nil那么named_scope将回退到使用默认顺序。

Railscasts在named_scopes上有一些很棒的信息。

通常,为Hash和Hash类对象提供默认值的方法是使用fetch

params.fetch(:sort){ :created_at }

很多人只是使用|| 虽然:

params[:sort] || :created_at

我宁愿fetch自己为更加明确,加上当它不破false是一个合法的值。

设置默认值的Ruby习语是:

@posts = Post.paginate :page => params[:page], :order => params[:sort] || "created_at"

但这种方法并不安全。 paginate方法不会打扰像"created_at; DROP DATABASE mydatabase;"这样的参数"created_at; DROP DATABASE mydatabase;" 相反,您可以使用有效排序参数的字典(未经测试):

sort_params = { "by_date" => "created_at", "by_name" => "name" }

@posts = Post.paginate :page => params[:page], :order => sort_params[params[:sort] || "by_date"]

这样URI变为:

http://localhost:3000/posts/?sort=by_date

我更喜欢这个成语:

@posts = Post.paginate :page=>page, :order=>order
...

def page
  params[:page] || 1
end

def order
  params[:order] || 'created_at ASC'
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM