I have two models with "has_many :through" association. It’s working good, but I need to add unique ordering for each of combination. Let’s say we have model Train and Carriages (Railway Carriage) and each train has unique combination of carriages
# /models/train.rb
class Train < ActiveRecord::Base
has_many :carriages, through: :combinations
end
# /models/carriage.rb
class Carriage < ActiveRecord::Base
has_many :trains, through: :combinations
end
# /models/combination.rb
class Combination < ActiveRecord::Base
belongs_to :train
belongs_to :carriage
end
# /controllers/trains_controller.rb
class TrainsController < ApplicationController
def shortcut_params
params.require(:train).permit(:name, :description, carriage_ids: [])
end
end
# /views/trains/_form.html.erb
<div class="field">
<%= f.label :carriage_ids, 'Choose Carriages' %><br>
<%= f.select :carriage_ids, Carriage.all.collect { |x| [x.name, x.id] }, {}, multiple: true, size: 6 %>
</div>
For example:
train_1 = carriage_5, carriage_4, carriage_1, carriage_3, carriage_2, carriage_6
train_2 = carriage_6, carriage_5, carriage_3, carriage_1, carriage_2, carriage_4
train_3 = carriage_1, carriage_2, carriage_3, carriage_4, carriage_6, carriage_5
In this example carriage_5 have:
- first place in train_1,
- second place in train_2,
- last place in train_3.
It’s mean I can’t use solution like this https://stackoverflow.com/a/19138677/4801165, because I don’t have parameter to order carriages.
In database I see that carriage_ids saving from 1 to 5 (from lowest to highest id), so may be there is solution to add ids one by one?
I hope there is easy solution to get correct ordering of carriage for each Train. Thanks