Search code examples
ruby-on-railsscopes

Rails 4 - ordering scopes


Im trying to make an app in Rails 4.

I have two scopes in my qualifications model:

scope :completed, ->{ where(pending: !true) }
scope :pending, -> { where(pending: true) }

I am trying to list them (newest first) in my view.

I have this view file:

<% Qualification.pending.sort_by.year_earned.asc.each do |qualification| %>
  <div class="row">
    <div class="col-md-12">
      <div class="profilequalifications">
        <%= qualification.current_study  %>
      </div>    
    </div>  
  </div>
<% end %>

<% Qualification.completed.sort_by(&:year_earned).each do |qualification| %>
  <div class="row">
    <div class="col-md-12">
      <div class="profilequalifications">
        <%= qualification.completed_award  %>
      </div>    
    </div>  
  </div>
<% end %>   

The second index works - but in the wrong order.

The first index - I have tried a million variations on the expression but can't find one that doesnt throw an error.

I have tried each of the above, and the following (each of which are following examples I found on this site):

<% Qualification.pending.sort_by(&:year_earned).reverse_order.each do |qualification| %>

<% Qualification.pending.sort_by(&:year_earned.reverse).each do |qualification| %>

<% Qualification.pending.sort_by('&:year_earned ASC').each do |qualification| %>


<% Qualification.pending.sort_by('year_earned ASC').each do |qualification| %>

Rather than list them all out - does anyone know how to list in ascending order?


Solution

  • I think you want Qualification.pending.order(year_earned: :asc).each do |qualification|

    See this for more information: http://apidock.com/rails/ActiveRecord/QueryMethods/order