How to order the second column from smallest to largest if the first column is equal rails

I would like to display the concentrations in ascending order (smallest to largest) if the temperature is equalled.

Here a table:

| T | C |

| 1 | 3 |

| 1 | 2 |

| 1 | 4 |

Gas Analyte Model

class GasAnalyte < ApplicationRecord
    has_many :gas_groups
    has_many :response_forms
end

Gas Group Model

class GasGroup < ApplicationRecord
    belongs_to :gas_analyte
    has_many :concentrations
    has_many :temperatures
end

Concentration Model

class Concentration < ApplicationRecord
    belongs_to :gas_group
    has_many :response_forms
    validates :value
end

Temperature Model

class Temperature < ApplicationRecord
    belongs_to :gas_group
    has_many :response_forms
    validates :value
end

ResponseForm Model

class ResponseForm < ApplicationRecord
    belongs_to :temperature
    belongs_to :concentration
    belongs_to :gas_analyte
    belongs_to :gas_group
end

View

<tbody>
    <%= form.fields_for :response_forms do |f| %>
        <%= render partial: 'fields', locals: {f: f} %>
    <% end %>
</tbody>

form is a gas analyte

fields View

<tr>
    <% res = ResponseForm.find(f.object.id) %>
    <td><%= Temperature.find(res.temperature.id).value %></td>
    <td><%= Concentration.find(res.concentration.id).value %></td>
<tr>

What could I do?

1 answer

  • answered 2019-08-13 05:39 Jonathan Bennett

    In your outer partial you want to specify the sorting of the response forms. This can be done by ordering them and then passing them into the fields_for:

    <tbody>
        <% sorted_fields = f.object.response_forms.left_join(:temperature, :concentration).order('temperatures.value', 'concentrations.value') %>
        <%= form.fields_for :response_forms, sorted_fields do |f| %>
            <%= render partial: 'fields', locals: {f: f} %>
        <% end %>
    </tbody>
    

    If this ordering is something you will frequently use, it would probably be worth moving into a scope in the ResponseForm model:

    class ResponseForm < ApplicationModel
    
        scope :tc_ordering, -> { left_join(:temperature, :concentration).order('temperatures.value', 'concentrations.value') }
    
    end
    
    # in your partial:
    <%= form.fields_for :response_forms, f.object.response_forms.tc_ordering do |f| %>