Ruby on rails Rails:按参数对查询进行排序?
我正在使用willpaginate运行一个简单的find all和分页,但是我也希望查询按用户排序。想到的第一个解决方案就是使用params[:sort]Ruby on rails Rails:按参数对查询进行排序?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在使用willpaginate运行一个简单的find all和分页,但是我也希望查询按用户排序。想到的第一个解决方案就是使用params[:sort] http://localhost:3000/posts/?sort=created_at+DESC @posts = Post.paginate :page => params[:page], :order => params[:sort] 但他的方法的问题是,查询默认为按ID排序,我希望它在 这是一种安全的排序方法吗?是否有
http://localhost:3000/posts/?sort=created_at+DESC
@posts = Post.paginate :page => params[:page], :order => params[:sort]
但他的方法的问题是,查询默认为按ID排序,我希望它在
这是一种安全的排序方法吗?是否有一种方法可以默认创建?通常,为散列和类似散列的对象提供默认值的方法是使用
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;”“
这样的参数。相反,您可以使用有效排序参数的字典(未测试):
这样URI就变成:
http://localhost:3000/posts/?sort=by_date
我将使用一个命名的作用域来提供默认顺序(从Rails 2.1开始提供) 您需要在您的Post模型中添加范围:
named_scope :ordered, lambda {|*args| {:order => (args.first || 'created_at DESC')} }
然后你可以打电话:
@posts = Post.ordered.paginate :page => params[:page]
上述示例将使用命名范围
(在DESC创建)中的默认顺序,但您也可以提供不同的顺序:
@posts = Post.ordered('title ASC').paginate :page => params[:page]
你可以利用罗穆洛的建议:
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
将返回使用默认顺序
关于命名范围有一些很好的信息。我更喜欢这个成语:
@posts = Post.paginate :page=>page, :order=>order
...
def page
params[:page] || 1
end
def order
params[:order] || 'created_at ASC'
end
如果有其他人遇到这种情况,则作用域的更新语法如下:scope:ordered,->(*args){order(args.first | |'created_at DESC')}
方法本身仍然很有用!
@posts = Post.paginate :page=>page, :order=>order
...
def page
params[:page] || 1
end
def order
params[:order] || 'created_at ASC'
end