1

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

Community
  • 1
  • 1
oleksandr
  • 56
  • 6
  • You could have a custom positions table and then join and order by that. There is also the possibility to do a custom order, but that will get messy when you add more models. Here's a [gist](https://gist.github.com/cpjolicoeur/3590737) that is about exactly that topic – Julia Will Jun 16 '16 at 16:25

2 Answers2

0

You can add a position attribute to your Combination model denoting the position of the Carriage within the Train.

Fred Willmore
  • 4,386
  • 1
  • 27
  • 36
0

I tried to use Fred Willmore advice but this additional column not need if you use nested forms to adding manually each element. You can find Gem here https://rubygems.org/gems/cocoon and use this nice guide with Standard Rails Forms https://github.com/nathanvda/cocoon/wiki/ERB-examples.

oleksandr
  • 56
  • 6