Same Model for Two belongs_to Associations migration Same Model for Two belongs_to Associations migration database database

Same Model for Two belongs_to Associations migration


You have to create the following migration:

rails g migration AddBuyerAndSellerToSales buyer:references seller:references

This should create the following migration file:

class AddBuyerAndSellerToSales < ActiveRecord::Migration  def change    add_reference :sales, :buyer, index: true, foreign_key: true    add_reference :sales, :seller, index: true, foreign_key: true  endend

If you use a database engine like PostgreSQL you have to tell the engine to which table the foreign key will point.

class AddBuyerAndSellerToSales < ActiveRecord::Migration  def change    add_reference :sales, :buyer, index: true   # foreign_key: true <= remove this!    add_reference :sales, :seller, index: true  # foreign_key: true <= remove this!    add_foreign_key :sales, :users, column: :buyer_id    add_foreign_key :sales, :users, column: :seller_id  endend

Hope this helps!


This is called a self join, and can be created as follows:

#app/models/sale.rbclass Sale < ActiveRecord::Base  belongs_to :buyer, class_name: 'User', foreign_key: :buyer_id  belongs_to :seller, class_name: 'User', foreign_key: :seller_idend

--

$ rails g migration CreateSales#db/migrate/create_sales______________.rbclass CreateSales < ActiveRecord::Migrate    def change        change_table :sales do |t|           t.references :seller           t.references :buyer        end    endend$ rake db:migrate