Rails 4: STI belongs to polymorphic STI

# Table: members
# source_id: integer
# source_type: string
class Member < ActiveRecord::Base
belongs_to :source, polymorphic: true
end

class GroupMember < Member
# we want to re-use existing source association.
belongs_to :group
end

class Group < Namespace
# I want query only GroupMembers that belongs to this group
has_many :group_members
end
class Member < ActiveRecord::Base  
belongs_to :source, polymorphic: true
end

class GroupMember < Member
belongs_to :group, class_name: 'Group', foreign_key: 'source_id'
end

class Group < Namespace
has_many :group_members, as: :source, class_name: 'GroupMember'
end
group = Group.first  
member = GroupMember.new
member.source = group
puts member.source_type
# => Namespace

Dmitriy Zaporozhets

Written by

Ruby developer, GitLab cofounder

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade