Ruby on rails - Reference the same model twice?

前端 未结 4 1652
长情又很酷
长情又很酷 2020-11-30 18:10

Is it possible to set up a double relationship in activerecord models via the generate scaffold command?

For example, if I had a User

4条回答
  •  悲&欢浪女
    2020-11-30 19:10

    The above answers, while excellent, do not create foreign key constraints in the database, instead only creating indexes and bigint columns. To ensure that the foreign key constraint is enforced, add the following to your migration:

    class CreatePrivateMessages < ActiveRecord::Migration[5.1]
        def change
            create_table :private_messages do |t|
              t.references :sender
              t.references :recipient
            end
    
            add_foreign_key :private_messages, :users, column: :sender_id, primary_key: :id
            add_foreign_key :private_messages, :users, column: :recipient_id, primary_key: :id
        end
    end
    

    This will ensure that the indices get created on the sender_id and recipient_id as well as the foreign key constraints in the database you're using.

提交回复
热议问题