使用范围ruby在轨道上排序多个帖子

时间:2015-08-24 04:45:12

标签: ruby-on-rails

我尝试使用ordered_by_titleordered_by_reverse_created_at在我的网页上订阅帖子。

我不知道我是否正确行事,但在我的post_controller上我有:

def ordered_by_title(order)

  @post = Post.order(:title)

end

在我的post.rb上我有:

default_scope { ordered_by_title('title DESC') }

这似乎很好地按照帖子的标题排序,但我不确定我怎么也可以通过同时创建的反向命令。关于我如何做到这一点的任何建议?

2 个答案:

答案 0 :(得分:0)

您可以使用scope inside another scope,但不能使用范围内的方法。将其写在Post模型中,如:

scope :ordered_by_title, -> { order(:title) }
default_scope { ordered_by_title.order('title DESC') }

答案 1 :(得分:0)

您可以在一个范围内完成所有操作。

# add the following line of code to post.rb
scope :order_by_title, -> {order(title: :desc, created_at: :desc)}

更新此行代码

@post = Post.order(:title)

@posts = Post.order_by_title

这将返回所有帖子标题降序。如果两个记录具有相同的标题,则最新的记录将首先显示。我向s添加了@post,因为它会返回多个帖子,因此@posts@post更有意义。