Rails 4范围没有正确排序

时间:2016-11-25 16:05:25

标签: ruby-on-rails sorting

这是我第一次在rails中使用scope。我试图在我的章节模型中通过一个名为:priority的字段对一个章节列表进行排序。我查看了范围文档,但我似乎无法弄清楚如何使该功能工作。

模型

class Chapter < ActiveRecord::Base
 belongs_to :book
 scope :priority_sort, -> { order(priority: :asc) }
end

控制器

@chapters = Chapter.all.priority_sort

和视图

<% @book.chapters.each do |chapter| %>
  <%= link_to chapter.title, [@book, chapter] %>
<% end %>

目前的观点是什么 优先级/ CHAPTER_TITLE

  -15
  About the authors

  3
  Chapter 18 Equal pay

  -13
  Chapter 2 Overview

  -4
  Chapter 11 Non-exempt employees: determining work time

  -11
  Chapter 4 Workers not covered by the FLSA

使用default_scope { order("priority ASC") }

查看的内容
  -15
  About the authors

  -14
  Chapter 1 Snapshot

  -13
  Chapter 2 Overview

  -12
  Chapter 3 Covered employers

  -11
  Chapter 4 Workers not covered by the FLSA

我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

<% @book.chapters.each do |chapter| %>
 <%= link_to chapter.title, [@book, chapter] %>
<% end %>

这是一个错误吗?如果没有,那就是因为你在控制器中使用了一些你不使用的东西。即

@chapters = Chapter.priority_sort.all

如果没有,那么您可以将其更改为

<% @book.chapters.priority_sort.each do |chapter| %>
  <%= link_to chapter.title, [@book, chapter] %>
<% end %>