Skip to content
  • ktmouk's avatar
    5b4a516c
    Fixed odd behavior of inverse_of with multiple belongs_to to same class · 5b4a516c
    ktmouk authored
    
    
    Fix: #35204.
    
    This PR added validation to `automatic_inverse_of` that foreign_keys are the same.
    
    If class has multiple `belongs_to` to same class, `automatic_inverse_of` can find the wrong `inverse_name`.
    
    ```ruby
    class Room < ActiveRecord::Base
      belongs_to :user
      belongs_to :owner, class_name: "User"
    end
    
    class User < ActiveRecord::Base
      has_one :room
      has_one :owned_room, class_name: "Room", foreign_key: "owner_id"
    end
    
    user = User.create!
    owned_room = Room.create!(owner: user)
    
    p user.room
    ```
    
    The current `automatic_inverse_of` validates the `reflection` that found from associations.
    However, its validation does not validate that foreign keys are the same.
    
    so this issue can be fixed by adding a validation of foreign keys.
    
    Co-authored-by: default avataralpaca-tc <alpaca-tc@alpaca.tc>
    Co-authored-by: default avatarcat2koban <taba.noritomo@moneyforward.co.jp>
    Co-authored-by: default avatarluccafort <konishi.tatsuro@moneyforward.co.jp>
    5b4a516c
    Fixed odd behavior of inverse_of with multiple belongs_to to same class
    ktmouk authored
    
    
    Fix: #35204.
    
    This PR added validation to `automatic_inverse_of` that foreign_keys are the same.
    
    If class has multiple `belongs_to` to same class, `automatic_inverse_of` can find the wrong `inverse_name`.
    
    ```ruby
    class Room < ActiveRecord::Base
      belongs_to :user
      belongs_to :owner, class_name: "User"
    end
    
    class User < ActiveRecord::Base
      has_one :room
      has_one :owned_room, class_name: "Room", foreign_key: "owner_id"
    end
    
    user = User.create!
    owned_room = Room.create!(owner: user)
    
    p user.room
    ```
    
    The current `automatic_inverse_of` validates the `reflection` that found from associations.
    However, its validation does not validate that foreign keys are the same.
    
    so this issue can be fixed by adding a validation of foreign keys.
    
    Co-authored-by: default avataralpaca-tc <alpaca-tc@alpaca.tc>
    Co-authored-by: default avatarcat2koban <taba.noritomo@moneyforward.co.jp>
    Co-authored-by: default avatarluccafort <konishi.tatsuro@moneyforward.co.jp>
Loading