Question

I have a controller that returns a queryset like so;

def show
  @docs = Docs.where("id > ?", params[:id]).order(:id).reverse_order
  respond to do |format|
    format.js
  end
end

In the rails console this returns my records in the correct order.

show.js.erb looks like this;

<% unless @docs.empty? %>
  $("#published").append("<%=raw escape_javascript(render(@docs)) %>");
<% end %>

EDIT: I'm using a partial like so and I believe the order is ignored here;

my index.html calls;

<%= render @outline.outline_docs %>

which renders **outline\_outline_doc.html.erb **;

<div class="well" data-doc="<%= outline_doc.id %>">
  <h4><%= link_to outline_doc.id, "" %></h4>
  <%= Time.at(outline_doc.created_at.to_i + 1) %>
  </br>
</div>

But instead of the items being displayed in the order specified in the controller (27,28,29,30) they are always displayed as (28,29,27,30). Any ordering specified is always ignored.

How can I ensure that the records retrieved are appended in the desired manner?

Was it helpful?

Solution

Try this

def show
  @docs = Docs.where("id >", params[:id]).all
  @docs.sort! { |a,b| a.id <=> b.id }
  respond to do |format|
    format.js
  end
end

The primary problem MAY be that the adapter that you use to connect to your DB does not respect ordering

EDIT: Responding to your comment: Lets try moving the ordering to a view:

<% unless @docs.empty? %>
  $("#published").append("<%=raw escape_javascript(render(@docs.sort! { |a,b| a.id <=> b.id })) %>");
<% end %>

EDIT2: PARTIALS

try rendering your partial like this

<%= render :partial => @outline.outline_docs, :collection => @docs.sort! { |a,b| a.id <=> b.id } %>

Alternatively (if you are sure the order is passed correctly in your existing code) just:

<%= render :partial => @outline.outline_docs, :collection => @docs %>

I didn't see how your outline is directly connected with @docs so you may try using :collections with @docs (if the second render call is the culprit):

$("#published").append("<%=raw escape_javascript(render(:partial => "PARTIAL NAME", :collection => @docs)) %>");
<% end %>

Don't forget to replace PARTIAL NAME with whatever the partial you want to render @docs in or use @docs instead of PARTIAL NAME if you have corresponsing to_partial_path

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top