Search code examples
ruby-on-railsrubyforeign-keysdestroy

Multiple Foreign Keys _ has_many


In Rails, I need a model to have a has_many with two foreign keys that need to be matched to make the list.

Ex:

Organization_Profiles

table structure

id : int
profile_id : int
organization_id : int

associations

belongs_to: :profile
belongs_to: :organization
has_many: :notifications, foreign_keys: [:profile_id, :organization_id], dependent: :destroy

Notifications

table structure

id : int
profile_id : int
organization_id : int
level : int
message : string

associations

belongs_to: :profile
belongs_to: :organization

How can I accomplish the above? From what I've researched, the foreign_keys: [] does not exist.


Solution

  • You can accomplish this without relying on the dependent command of an association. The best way I can think of is to 'clean out' the associations when the action is taken to disassociate the Profile from an Organization. You could have an inverse method in Organization.

    class Profile < ActiveRecord:Base
    
      def method_that_disassociates_from(inputted_organization)
        self.organizations.delete(inputted_organization)
        self.notifications.where(organization_id: inputted_organization.id).destroy_all
      end
    
    end