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

Comments

Popular Posts

How to pass hash in Postman

nginx: unrecognized service

Bootstrap Select Picker append add new item if search not exist

Reading Excel Sheets using "Roo" gem in ruby on rails

Add CORS to Nginx on AWS Elastic Beanstalk

Enable gzip compression on Elastic Beanstalk with nginx

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Get video duration by URL in Ruby on Rails

site-enables nginx setting in ruby in rails