2010-05-19 29 views
8

我想知道是否可以在视图中指定顺序(即: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 %> 

在我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 

更新:对于改变@ 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 

更新2:我想我应该指出,这个代码是在问题显示视图。 views/questions/show.html.erb.

+0

编辑我的回答:] – 2010-05-19 18:57:18

回答

10

您可以使用:

<% unless @questions.empty? %> 
    <% @questions.each do |question| %> 
     # ... 
    <% end %> 
<% end %> 
在你看来

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

showQuestionsControllerindex方法。

+0

这不是视图的实际语法吗?它需要<%不是吗? – bgadoci 2010-05-19 19:29:55

+0

是的,你需要它... – 2010-05-19 20:34:16

2

你应该使用的

<% @questions.each do |question| %> 

代替

<% @user.questions.each do |question| %> 

编辑。您可以使用以下方法之一避免零错误。

<% @questions.each do |question| %> 


<% end unless @questions.blank? %> 

OR

<% for question in @questions %> 


<% end unless @questions.blank? %> 
+0

当我这样做,我得到一个错误。我更新了我的问题。 – bgadoci 2010-05-19 16:57:12

+0

请检查我的EDITED答案。 – Salil 2010-05-20 05:40:15

+0

不错......它确实摆脱了这个错误,但它现在并没有吸引用户的疑问。我如何发送:具有请求的用户? – bgadoci 2010-05-20 16:32:33

0

使用变量@questions而不是@user.questions在您的视图。

+0

当我这样做时,我得到一个错误。我更新了我的问题。 – bgadoci 2010-05-19 16:57:50

4

一个简单的方法来做到这一点是使用reverse_each,而不是each

<% @user.questions.reverse_each do |question| %> 

你得到你的降序排列的问题,而不要触摸控制器东西。