更改帖子循环顺序的链接
Links to change ordering of a posts loop
我正在尝试在我的页面中获得链接,这些链接允许我更改我的帖子的显示顺序。类似于 Reddit 上的 'Recent'、'Hot' 和 'Oldest'。
我目前默认有
PostsController.rb
def index
@posts = Post.order('created_at DESC').all.paginate(page: params[:page], per_page: 20)
end
我将如何添加指向一种方法的链接以将帖子流向 ASC 反向或显示按视图等模型上的特定列降序排列的帖子?
乔恩
在您的应用中使用 will_paginate
gem 双向 Sorting
和 Paginate
。访问这个 link 来实现它 https://github.com/mislav/will_paginate .
首先您要删除 all
以便分页效果更好。
def index
@posts = Post.order('created_at DESC').paginate(page: params[:page], per_page: 20)
end
那你可以用一个变量来控制顺序。重要的是在传递给 mysql.
之前进行消毒
def index
sort_by = ActiveRecord::Base::sanitize(params.permit(:sort_by))
@posts = Post.order(sort_by).paginate(page: params[:page], per_page: 20)
end
我会在模型中创建一些范围和一个方法来处理所有的可能性,
# Post.rb
scope :recent, -> { order(created_at: :desc) }
scope :hot, -> { order(something: :desc) }
scope :oldest, -> { order(created_at: :asc) }
def self.sort_by(sort_param)
case sort_param
when 'recent'
recent
when 'hot'
hot
when 'oldest'
oldest
else
all
end
end
# controller
@posts = Post.sort_by(params[:order]).paginate(page: params[:page], per_page: 20)
因为我是白名单,所以我真的不需要清理,任何错误的参数都会 return 默认顺序。
如果你愿意,你可以使用 #send
并将方法名称添加到白名单数组,但你需要确保范围存在
def self.sort_by(sort_param)
if %w(recent hot oldest).include? sort_param
send sort_param
else
all
end
end
我正在尝试在我的页面中获得链接,这些链接允许我更改我的帖子的显示顺序。类似于 Reddit 上的 'Recent'、'Hot' 和 'Oldest'。
我目前默认有
PostsController.rb
def index
@posts = Post.order('created_at DESC').all.paginate(page: params[:page], per_page: 20)
end
我将如何添加指向一种方法的链接以将帖子流向 ASC 反向或显示按视图等模型上的特定列降序排列的帖子?
乔恩
在您的应用中使用 will_paginate
gem 双向 Sorting
和 Paginate
。访问这个 link 来实现它 https://github.com/mislav/will_paginate .
首先您要删除 all
以便分页效果更好。
def index
@posts = Post.order('created_at DESC').paginate(page: params[:page], per_page: 20)
end
那你可以用一个变量来控制顺序。重要的是在传递给 mysql.
之前进行消毒 def index
sort_by = ActiveRecord::Base::sanitize(params.permit(:sort_by))
@posts = Post.order(sort_by).paginate(page: params[:page], per_page: 20)
end
我会在模型中创建一些范围和一个方法来处理所有的可能性,
# Post.rb
scope :recent, -> { order(created_at: :desc) }
scope :hot, -> { order(something: :desc) }
scope :oldest, -> { order(created_at: :asc) }
def self.sort_by(sort_param)
case sort_param
when 'recent'
recent
when 'hot'
hot
when 'oldest'
oldest
else
all
end
end
# controller
@posts = Post.sort_by(params[:order]).paginate(page: params[:page], per_page: 20)
因为我是白名单,所以我真的不需要清理,任何错误的参数都会 return 默认顺序。
如果你愿意,你可以使用 #send
并将方法名称添加到白名单数组,但你需要确保范围存在
def self.sort_by(sort_param)
if %w(recent hot oldest).include? sort_param
send sort_param
else
all
end
end