链接以更改帖子循环的顺序 [英] Links to change ordering of a posts loop

查看:68
本文介绍了链接以更改帖子循环的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在页面中实现链接,使我可以更改帖子显示的顺序。类似于Reddit上的最近,热门和最旧。

I'm trying to achieve links in my page that allow me to change the order that my posts display in. Similar to 'Recent', 'Hot' and 'Oldest' on Reddit.

我当前默认情况下

PostsController.rb

  def index
      @posts = Post.order('created_at DESC').all.paginate(page: params[:page],      per_page: 20)
  end

我将如何添加指向方法的链接,以将帖子的流向ASC或显示帖子在模型上按特定列降序排列,例如视图吗?

How would I go about adding links to a method to reverse the flow of posts to ASC or to display posts descending by a specific column on the model like views?

Jon

推荐答案

我将在模型中创建一些范围和方法来处理所有可能性,

I'd create some scopes and a method in the model to handle all the possibilities,

# 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)

由于我已列入白名单,因此我真的不需要清理,任何错误的参数都会返回默认顺序。

Since I'm whitelisting, I don't really need to sanitize, any wrong param will return the default order.

如果您希望可以使用 #send 并将方法名称添加到白名单数组,但是您需要确保范围存在

If you want you could use #send and add method names to the whitelist array, but you need to make sure that the scope exists

def self.sort_by(sort_param)
  if %w(recent hot oldest).include? sort_param
    send sort_param
  else
    all
  end
end

这篇关于链接以更改帖子循环的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆