【问题标题】:allowing users to change the order of a scope允许用户更改范围的顺序
【发布时间】: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


    【解决方案1】:

    基本上有两种方法可以做到这一点:

    1. 纯前端,用js。如果您不想自己编写(例如 DataTables),可以使用一些具有排序功能的现有 js 插件。您可能需要创建一个具有不同属性的表格才能使其工作。

    2. 后端,使用 ajax。自己编写或使用 filterrific 之类的东西,它使用范围进行过滤和排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2013-11-30
      • 2017-06-03
      • 2016-12-10
      • 2012-08-23
      相关资源
      最近更新 更多