0

我是一个菜鸟,我试图简单地获取数据库中的所有记录并按字母顺序显示它们。每当我显示索引页面时,记录总是按其 id 降序排序。我使用控制台尝试调用 EvalTest.order("name") 并再次获得按 id 降序排列的记录,而不是按名称排序。我是否需要在名称列上添加索引以按它排序?这似乎答案应该很容易,但我似乎无法弄清楚......

这是我的代码:

User Model:

    class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation
  has_secure_password
  has_many :eval_tests

  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence:   true,
                     format:     { with: VALID_EMAIL_REGEX },
                     uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true
  after_validation { self.errors.messages.delete(:password_digest) }

  private

    def create_remember_token
      self.remember_token = SecureRandom.urlsafe_base64
    end
end

Eval_Test 模型:

class EvalTest < ActiveRecord::Base
  attr_accessible :description, :name
  belongs_to :user

  validates :user_id, presence: true
  validates :name, presence: true
  validates :description, presence: true, length: { maximum: 350 }
  default_scope order: 'eval_tests.created_at DESC'
end

评估测试控制器:

class EvalTestsController < ApplicationController
  def show
    @eval_test = EvalTest.find(params[:id])
  end

  def new
    @eval_test = EvalTest.new
  end

  def index
    @eval_tests = EvalTest.order("name")
  end

  def create
    @eval_test = current_user.eval_tests.build(params[:eval_test])
    if @eval_test.save
      flash[:success] = "Nouveau test cree!"
      redirect_to @eval_test
    else
      render 'new'
    end
  end
end

评估测试 index.html.erb:

<% provide(:title, 'Index des tests') %>
<h1>Index des tests</h1>

<ul class="eval_tests">
  <% @eval_tests.each do |eval_test| %>
    <li>
      <%= link_to eval_test.name, eval_test %>
    </li>
  <% end %>
</ul>
4

1 回答 1

1

发生这种情况是因为您在模型中使用了默认范围。试试 @eval_tests = EvalTest.reorder("name") 这应该可以解决您的问题。

于 2013-07-27T00:44:16.407 回答