I am trying to get some polymorphic associations to work properly but I am unable to get them right. Currently they give me whatever the ID matches for both tables instead of the direct relation.
class User < ApplicationRecord
belongs_to :origin, polymorphic: true
has_one :customer, foreign_key: :id, primary_key: :origin_id, class_name: "Customer"
has_one :employee, foreign_key: :id, primary_key: :origin_id, class_name: "Employee"
end
class Customer < ApplicationRecord
has_one :user, class_name: "User", foreign_key: :origin_id
end
class Employee < ApplicationRecord
has_one :user, class_name: "User", foreign_key: :origin_id
end
If I do:
user = User.create(origin: Customer.find(1))
user.customer # => #<Customer:0x000000014a78d2c8>
# I expect that the code below to be nil but it is not
user.employee # => #<Employee:0x000000014a78d2c8>
Does anyone know how can I get the proper association? Thanks in advance.
In the rails guides there is example with
has_manypolymorphic associationshas_onehas almost the same code, also read more aboutbelongs_toassociation optionsIn any case you need such schema migration:
Output should be something like this