'Sort Records according to associated data column
I'm feeling really dump that how could I sort records according to associated data column
I'm fetching records in my controller like
@collection = @collection.includes(:countries).page(params[:page]).per(per_page)
and in my index page I'm doing like this
<tbody>
<% @collection.each do |price_mapping| %>
<tr>
<td><%= price_mapping.countries.pluck(:name).join(', ') %></td>
<td><%= price_mapping.currency.code %></td>
<td><%= price_mapping.program.name %></td>
<td><%= price_mapping.active %></td>
<td><%= price_mapping.default %></td>
</tr>
<% end %>
</tbody>
with line
price_mapping.countries.pluck(:name).join(',')
I got countries' names like
Åland Islands, Algeria, Zimbabwe
now I want to sort all my @collections according to the first country name for example, if a collection has countries [zimbabwe, Afghanistan, pakistan] it will be the last record and which have countries like [Afghanistan, zimbabwe, canada] it will be the first one.
Solution 1:[1]
we can get it simply by using Order with includes
@collection = @collection.includes(:countries).order('countries.name ASC').page(params[:page]).per(per_page)
I don't know when I tried to do this with join I got repeated records and I have to add distinct and after that order did not work.
Solution 2:[2]
Maybe smth like this?
@collection = @collection.joins(:countries).order('countries.name ASC').page(params[:page]).per(per_page)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Humayun Naseer |
| Solution 2 | Leon |
