views:

76

answers:

3

I am wondering if it is possible to dictate the order (i.e. :order => 'created_at DESC') within the view. I realize that logic in the view is not ideal but I seem to be having some problems locating where to affect this output.

For instance, here is my code:

<% @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 %>

In my QuestionsController I have the following index action but it is not affecting the output from the code above.

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

UPDATE: With respect to changing the @user.questions to @questions I get this error:

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

UPDATE 2: I guess I should mention that this code is in the questions show view. views/questions/show.html.erb.

+1  A: 

you should use

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

instead of

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

EDITED. You can avoid nil error by using one of the following ways.

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


<% end unless @questions.blank?  %>

OR

<% for question in @questions %>


<% end unless @questions.blank?  %>
Salil
When I do that I get an error. I updated my question.
bgadoci
please check my EDITED Answer.
Salil
Nice...that did get rid of the error but it is not pulling in the user's questions now. How do I send :user with the request?
bgadoci
A: 

Use the variable @questions instead of @user.questions in your view.

KandadaBoggu
When I do that I get an error. I updated my question.
bgadoci
+2  A: 

You can use:

<% unless @questions.empty? %>
   <% @questions.each do |question| %>
      # ...
   <% end %>
<% end %>

in your view and

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

inside show or index method of QuestionsController.

j.
That is not the actual syntax for the view right? It needs the <% doesn't it?
bgadoci
Yes, you need it...
j.
Ah, actually that all worked with the exception of your last line which I had to change to `UsersController` `index` and `show` actions.
bgadoci