how can I do self-reference with ruby on rails?

后端 未结 4 733
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 12:34

I want to self-referentiate a model in a RoR app but, I don\'t know exactly how. I want to save a linked list where the next node has the id of the previous one. how can I d

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 13:00

    rails 5

    add column xxx_id in users table:

    in migration file:

    add_reference :users, :xxx, index: true
    

    and add code in User model

    has_many :users, class_name: 'User', foreign_key: 'xxx_id'
    belongs_to :manager, class_name: 'User', foreign_key: 'xxx_id'
    

    If you don't have a manager for every user, you need to add optional: true.

    'foreign_key' is not necessary. By default this is guessed to be the name of this class in lower-case and “_id” suffixed.

    if foreign_key is user_id, user don't have manager necessary. the result is:

    has_many :users, class_name: 'User'
    belongs_to :manager, class_name: 'User', optional: true
    

提交回复
热议问题