1

I have a problem joining two models in a n..n association.

I have the following associations in the context:

  • Proposal n..n Product
  • Proposal n..n Project
  • Proposal n..n NewProject

And similarly with this, I have:

  • Order n..n Product
  • Order n..n Project
  • Order n..n NewProject

Well, the join model has the same attributes on both cases, but the partial for each of them is different.

Is there a way to do a single join model (Item), that would store all the data, and yet usable with the three different alias in Order and Proposal?

I tried to code it like this, but didn't work..

proposal.rb

    class Proposal < ActiveRecord::Base
      ...
      has_many :items
      has_many :products, through: :items, source: :requisition, source_type: "Produto"
      has_many :projects, through: :items, source: :requisition, source_type: "Projeto"
      has_many :projects, through: :items, source: :requisition, source_type: "Novo"
      ...
    end

order.rb

    class Order < ActiveRecord::Base
      ...
      has_many :items, as: :requisition, dependent: :destroy
      has_many :products, through: :items, source: :requisition, source_type: "Produtos"
      has_many :projects, through: :items, source: :requisition, source_type: "Projetos"
      has_many :projects, through: :items, source: :requisition, source_type: "Novos"
      ...
    end

product.rb

    class Product < ActiveRecord::Base
      has_many :items, as: :piece, dependent: :destroy
      has_many :orders, through: :items, source: :piece, source_type: 'Order'
      has_many :proposals, through: :items, source: :piece, source_type: 'Proposal'
      ...
    end

project.rb

    class Project < ActiveRecord::Base
      has_many :items, as: :piece, dependent: :destroy
      has_many :orders, through: :items, source: :piece, source_type: 'Order'
      has_many :proposals, through: :items, source: :piece, source_type: 'Proposal'
      ...
    end

item.rb

    class Item < ApplicationRecord
      belongs_to :piece, polymorphic: true
      belongs_to :requisition, polymorphic: true
      ...
    end

I expect to unify this associations, to clear some tables, and try to speed up the app.

  • Why do you think it would speed up the app? you are adding more complexity using polymorphic relationships. If your motivation is just speed up the app I think you'll have better results optimizing other things (use some profiler app like rack-miniprofiler to get an insight of the rendering and querying times for example and optimize that instead) – arieljuod Feb 07 '19 at 19:00
  • I thought that using one model instead of 6 would simplify some things in the app, buth thanks for the tip! – Leandro Pons Malheiros Feb 07 '19 at 19:34
  • Polymorphism is a pretty good way to ruin the performance of your app due to the lack of effective foreign keys and eager loading support. Having separate join tables is far more performant. – max Feb 07 '19 at 20:00

0 Answers0