无法对活动记录进行排序

时间:2013-07-27 00:11:33

标签: ruby-on-rails sorting activerecord

我是一个noobie,我试图简单地获取数据库中的所有记录并按字母顺序显示它们。每当我显示索引页面时,记录总是按其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

EvalTest控制器:

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>

1 个答案:

答案 0 :(得分:1)

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