All threads / how to model on rails that a supplier can be a customer and a customer can also be a supplier. ?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

how to model on rails that a supplier can be a customer and a customer can also be a supplier. ?

francel.webdev asked in Rails

Good evening everyone,

Here's my problem:

I have 2 tables, suppliers and customers who are all companies.

how to model on rails that a supplier can be a customer and a customer can also be a supplier. ?

Thank you

Hi, I think I had a simalr issue while dealing with and employee (User) and manger (also User) relationship, my solution was to use a self-jion or self referential association

migration

    add_reference :users, :manager, foreign_key: { to_table: :users }, index: true

model

  belongs_to :manager, class_name: "User"

Your model is wrong it's better to have a model named partner for example which has a partner type. Now you can seed it with partner types like Vendor, Customer, Supplier Both, whatever you want

class CreatePartnerTypes < ActiveRecord::Migration[5.2]
  def change
    create_table :partner_types do |t|
      t.string :name
      t.timestamps
    end
    add_index :partner_types, :name,  unique: true
  end
end

class CreatePartners < ActiveRecord::Migration[5.2]
  def change
    create_table :partners do |t|
      t.references :company
      t.references :partner_type
      t.string :name
      t.string :address
      t.string :postal_code
      t.string :city
      t.references :state
      t.timestamps
    end
  end
end


Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 52,887+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.