user671054
user671054

Reputation:

multiple belongs_to relationship to three model

The situation is this way..

class Organization < ActiveRecord::Base

  has_many :role_memberships
  has_many :roles
  has_many :users, :through => :role_memberships, :uniq => true

end

class User

 has_many :role_memberships
  has_many :organizations, :through => :role_memberships, :uniq => true
  has_many :roles, :through => :role_memberships, :uniq => true 

end

class RoleMembership < ActiveRecord::Base

  belongs_to :organization
  belongs_to :role
  belongs_to :user

end

class Role < ActiveRecord::Base
  belongs_to :organization
  has_many :role_memberships
  has_many :users, :through => :role_memberships, :uniq => true
end

The QUESTION is how do I populate all the three foreign-keys in rolemembership table..when I do org.users.push(u) this create a record but role_id is left out...

Upvotes: 1

Views: 1038

Answers (1)

Ireneusz Skrobis
Ireneusz Skrobis

Reputation: 1533

In this case I will probably create RoleMembership object itself, like this:

RoleMembership.create(:organization_id => org.id, :role_id => role.id, :user_id => user.id)

Upvotes: 1

Related Questions