2010-05-19 60 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| %> 

你得到你的降序排列的問題,而不要觸摸控制器東西。