has_many association with polymorphic in ruby on rails
rails g model member user_id:integer invitable_id:integer invitable_type:string
class Member < ActiveRecord::Base
belongs_to :user
belongs_to :invitable, polymorphic: true
end
User can join many communities, groups and meeting rooms, so the has many polymorphic association will look like as:-
class User < ActiveRecord::Base
has_many :members, dependent: :destroy
has_many :community_members, through: :members, source: :invitable, source_type: 'Community'
has_many :group_members, through: :members, source: :invitable, source_type: 'Group'
has_many :meeting_rooms_members, through: :members, source: :invitable, source_type: 'MeetingRoom'
has_many :meeting_rooms, dependent: :destroy
end
class Member < ActiveRecord::Base
belongs_to :user
belongs_to :invitable, polymorphic: true
end
User can join many communities, groups and meeting rooms, so the has many polymorphic association will look like as:-
class User < ActiveRecord::Base
has_many :members, dependent: :destroy
has_many :community_members, through: :members, source: :invitable, source_type: 'Community'
has_many :group_members, through: :members, source: :invitable, source_type: 'Group'
has_many :meeting_rooms_members, through: :members, source: :invitable, source_type: 'MeetingRoom'
has_many :meeting_rooms, dependent: :destroy
end
Comments
Post a Comment