'Rails polymorphic association without using id column (using different column)

I have a polymorphic table with signable_id and signable_type.

 Class Login
   belongs_to :signable, polymorphic: true
 end

the signable can be either User or Account.

Class User
  has_many :logins, as: :signable
end

Class Account
  has_many :logins, as: :signable
end

The logins table will have signable_id which can be either user_id or account_id. But my problem is I will only get account_identifier and I cannot get account_id. Is it possible to use account_identifier as a key for polymorphic association instead if account id column.



Solution 1:[1]

No. Its not possible.

While you can use the primary_key: and foreign_key: options to accomodate for non-standard naming the settings are per assocation and cannot be configured per class of a polymorphic assocation.

# change the name of the column on the other tables
class Login
  belongs_to :signable, 
    polymorphic: true,
    primary_key: :uuid 
end

# change the name of the column on this tables
class Login
  belongs_to :signable, 
    polymorphic: true,
    foreign_key: :signable_uuid
end

You have to remember that a polymorphic assocation doesn't even know about all the classes it can associate with and this feature would making generating the join queries near impossible.

It is possible though if you setup two normal belongs_to assocations instead of a single polymorphic assocation.

class Login
  belongs_to :user, 
     optional: true
  belongs_to :account, 
     optional: true,
     primary_key: :account_identifier
end

Class User
  has_many :logins
end

Class Account
  has_many :logins, foreign_key: :account_identifier
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1