guys we are building a sort of address book, we have Users, Contacts and a parent Table called UserEntity. We want to relate them in a many-to-many association through a table called Relationship, this relations have to be in a self related in UserEntity table.
One User has many Contacts and one Contact has many Users.
Later on we need relate new models with Users so the Relationship model must be polymorphic. We already built this:
class UserEntity < ActiveRecord::Base
self.table_name = "users"
end
class User < UserEntity
has_many :relationships, as: :relatable
has_many :contacts, through: :relationships, source: :relatable, source_type "Contact"
end
class Contact < UserEntity
has_many :relationships, as: :relatable
has_many :users, through: :relationships, source: :relatable, source_type "User"
end
class Relationship < ActiveRecord::Base
belongs_to :user
belongs_to :relatable, polymorphic: true
end
but when we try to save the association user.contacts << contact
the relatable_type
field saves "UserEntity" value and not "Contact" or "User" value. We already tried to do this without any favorable results http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations
How can we make that relatable_type
value saves the model name ("Contact" || "User") and not the STI parent model name ("UserEntity")?