订购.each会导致视图

bga*_*oci 8 ruby ruby-on-rails

我想知道是否可以在视图中指定顺序(即:order =>'created_at DESC').我意识到视图中的逻辑并不理想,但我似乎在定位影响此输出的位置时遇到了一些问题.

例如,这是我的代码:

<% @user.questions.each do |question| %>
  <%= link_to_unless_current h (question.title), question %>
   Created about <%= time_ago_in_words h(question.created_at) %> ago
   Updated about <%= time_ago_in_words h(question.updated_at) %> ago

   <%= link_to 'Edit', edit_question_path(question) %> | 
   <%= link_to 'Destroy', question, :confirm => 'Are you sure?', :method => :delete %>

<% end %>
Run Code Online (Sandbox Code Playgroud)

在我的QuestionsController中,我有以下索引操作,但它不影响上面代码的输出.

class QuestionsController < ApplicationController 

def index

    @questions = Question.all(:order => 'created_at DESC', :limit => 20)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @questions }
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

更新:关于将@user.questions更改为@questions,我收到此错误:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
Run Code Online (Sandbox Code Playgroud)

更新2:我想我应该提一下这段代码是在问题展示视图中. views/questions/show.html.erb.

Ju *_*ira 11

您可以使用:

<% unless @questions.empty? %>
   <% @questions.each do |question| %>
      # ...
   <% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

在你的视野中

@questions = Question.all(:order => 'created_at DESC', :limit => 20)
Run Code Online (Sandbox Code Playgroud)

内部showindex方法QuestionsController.


PEF*_*PEF 5

一个简单的方法是使用reverse_each而不是each

<% @user.questions.reverse_each do |question| %>
Run Code Online (Sandbox Code Playgroud)

您将按降序排列问题,并且不要触摸控制器中的任何内容。