0

I have two tables: offers and tests.

But I need to have three join tables like, offers_tests_1, offers_tests_2, and offers_tests_3. This is because of a business requirement that an offer can have three combinations (packages) of tests.

Can we do this in Rails? For one join table, I could do it using the has_and_belongs_to_many association in the models with f.collection_select tag in the view, with :multiple => true.

Worst case, I could set up three tables tests_1, tests_2 and tests_3 with the same data. I want to avoid this.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
user1575148
  • 561
  • 6
  • 28

1 Answers1

0

Yes you can You can do it in model when defining your relationships. Like this.

In model Offer.rb

has_many :offers_tests_1
has_many :offers_tests_2
has_many :tests, through: :offers_tests_1
has_many :tests, through: :offers_test_2

in model Tests.rb

has_many :offers_tests_1
has_many :offers_tests_2
has_many :offers, through: :offers_tests_1
has_many :offers, through: :offers_test_2

enjoy

Pradeep Sapkota
  • 2,041
  • 1
  • 16
  • 30
  • I am going with this approach, but the view is still a problem. I have the following -- `<%= form_for(@offer) do |f| %> <%= f.fields_for :offers_tests_1 do |ot| %> <%= ot.collection_select(:test_id, Test.all, :id, :property, {include_hidden: false}, :multiple => true) %> <% end %> <% end %>` The error I have is -- Field doesn't have a default value – user1575148 Aug 03 '16 at 12:11
  • not fields_for :offers_tests_1 use fields_for :tests – Pradeep Sapkota Aug 03 '16 at 14:20
  • Where in the collection_select do I specify the association? I have three associations and three join tables. If I use fields_for :tests, Rails is inserting data into the third join table. – user1575148 Aug 03 '16 at 19:52