【发布时间】:2017-09-03 17:49:28
【问题描述】:
我只为我的项目使用过静态默认范围,而我最近想创建一个动态范围功能,用户可以在其中单击按钮或使用下拉菜单来更改他们查看列表的顺序。
到目前为止,我遇到了一些方法,例如使用取消范围和设置新范围,并看到重新排序。我正在查看文档,但我也不确定如何让用户能够选择。我会在相应的 HTML.erb 文件中使用 Link_to 或 button_to 之类的东西吗?
在我的 post.rb 文件中,它看起来像这样
default_scope { order(created_at: :desc) }
scope :ordered_by_title, -> { reorder(title: :asc) }
scope :ordered_by_reverse_created_at, -> { reorder(created_at: :ASC)}
我在默认值下添加了那些其他范围,因为我假设有人会设置他们想要的范围,并且一旦用户单击或从呈现的页面中选择它,视图就会调用/激活它们。
在我的post_controller.rb
def index
@posts = Post.all
end
在我的index.html.erb 视图中
我有以这种方式呈现的帖子列表,如果它不适用于我想做的事情,有人可以告诉我一个更好的方法吗?
# <some way for user to choose those defined scopes and render the new page would go here>
<% @posts.each do |post| %>
<div class="media">
<div class="media-body">
<h4 class="media-heading">
<%= link_to post.title, post %>
<small> <%= post.body %> </small>
</h4>
</div>
</div>
<% end %>
【问题讨论】:
标签: ruby-on-rails scope