简体   繁体   中英

Same Model for Two belongs_to Associations migration

How do I create a migration for a model that has two references to the same model.

I have a user model with two roles, buyer and seller, I also have a sales model so each sale should have one buyer and one seller.

I've seen this answer that would suggest my sales model should look like

class Sale < ActiveRecord::Base
  belongs_to :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

but I don't know how to create the migration and get it to work...!

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
  end
end

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
  end
end

Hope this helps!

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

#app/models/sale.rb
class Sale < ActiveRecord::Base
  belongs_to :buyer, class_name: 'User', foreign_key: :buyer_id
  belongs_to :seller, class_name: 'User', foreign_key: :seller_id
end

--

$ rails g migration CreateSales

#db/migrate/create_sales______________.rb
class CreateSales < ActiveRecord::Migrate
    def change
        change_table :sales do |t|
           t.references :seller
           t.references :buyer
        end
    end
end

$ rake db:migrate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM