Write a migration with reference to a model twice

后端 未结 2 889
情书的邮戳
情书的邮戳 2021-02-04 21:16

I have a message model (Message) and this models as a userTo and userFrom, so two references to User. How can i write the migration? My user model is User.

Thank you

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 21:33

    In the migration, create two different columns for each kind of user. For example:

    add_column :messages, :sender_id, :integer
    add_column :messages, :receiver_id, :integer
    

    Then in the model, that's where the logic to map each column to the User class happens:

    belongs_to :sender, :class_name => 'User'
    belongs_to :receiver, :class_name => 'User'
    

    Of course, use your own words for sender and receiver, but Rails will automatically associate sender to the sender_id column (and the same logic for receiver)

    You will then be able to interact with both user user.sender and user.receiver.

提交回复
热议问题