Thursday, March 22, 2018

Rails order by association being ignored

Leave a Comment

I'm trying to order by two columns, one is an association column which is being ignored, not implemented. Is it possible to order by association in a loop?

Loop

<% @info.each do |data| %>  <% data.selections.size.times do |i| %>   <% unless data.progressions.blank? %>     <% data.progressions.order_scope.in_groups_of(7)[i].each_with_index do |e, index| %>     <% if index == 0 %>       <%= e.selection.name rescue 0 %>     <% end %>     <%= Time.at(e.assessment.date/1000).strftime("%d/%m/%Y") rescue 0 %>   <% end %>   <% end %>  <% end %> <% end %> 

Model

belongs_to :selection, primary_key: 'selection_id', foreign_key: 'selection_id', optional: true belongs_to :assessment, primary_key: 'assessment_id', optional: true  scope :order_scope, -> { order('selection_id').joins(:assessment).order('assessments.date') } 

This is the output the previous code outputs, which seems to be randomly placing the dates instead of in order.

|name 1|     0    |0|0|0|02/01/2018|15/01/2018|23/01/2018|  |name 2|28/02/2018|0|0|0|02/01/2018|15/01/2018|21/01/2018| 

2 Answers

Answers 1

I think it is because progressions could have the same selection_id,when you order them, the result can be different. Try adding another unique attribute/column into the order, for example created_at or id, so that the order is always unique.

scope :order_scope, -> { order('selection_id, created_at').joins(:assessment).order('assessments.date') } 

Answers 2

So, what you're trying to do is basically order by 2 columns and use the result to output something? Yes, it can be done. Thing is, I would recommend using SQL instead, because in Ruby methods make it much less readable.

Execute this query in ruby:

SELECT * FROM selections s JOIN assessments a ON s.selection_id = a.selection_id ORDER BY a.date [DESC], s.selection_id [DESC]

[DESC] is optional keyword setting order in descending manner (ascending is default).

Result should be what you're looking for.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment