FlechMe
FlechMe

Reputation: 333

Rails multiple polymorphic associations in memberships

I have two table "users" and "structures". I'd like to create a relation between them in this way :

A structure could have many users as members A structure could have many structures as members

So a user can be members of many structures a structure can be members of many structures

I create a table named "Memberships" with two polymophics associations :

create_table :memberships do |t|
  t.references :is_memberable, index: true, polymorphic: true
  t.references :has_memberable, index: true, polymorphic: true

  t.string :kind

  t.timestamps
end

But what should I do in my model ?

Upvotes: 2

Views: 443

Answers (1)

FlechMe
FlechMe

Reputation: 333

Here is the solution :

User.rb

class User < ActiveRecord::Base

  has_many :is_memberships, :as => :is_memberable, :class_name => 'Membership'
  has_many :is_members_structures, through: :is_memberships, source: :is_memberable, source_type: 'Structure'
end

Membership.rb

class Membership < ActiveRecord::Base
  belongs_to :is_memberable, polymorphic: true
  belongs_to :has_memberable, polymorphic: true
end

Structure.rb

class Structure < ActiveRecord::Base

  has_many :is_memberships, :as => :is_memberable, :class_name => 'Membership'
  has_many :has_memberships, :as => :has_memberable, :class_name => 'Membership'
end

Upvotes: 1

Related Questions