Home > Mobile >  Sort Records according to associated data column
Sort Records according to associated data column

Time:04-08

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.

CodePudding user response:

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.

CodePudding user response:

Maybe smth like this?

@collection = @collection.joins(:countries).order('countries.name ASC').page(params[:page]).per(per_page)

  • Related