多个belongs_to关系到三个模型

时间:2011-04-12 05:48:59

标签: ruby-on-rails models belongs-to

情况就是这样......

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

QUESTION是如何在rolemembership表中填充所有三个外键的...当我执行org.users.push(u)时,这会创建一条记录,但是却省略了role_id ...

1 个答案:

答案 0 :(得分:1)

在这种情况下,我可能会创建RoleMembership对象,如下所示:

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