拥有并拥有3个型号的许多人

blo*_*ira 3 ruby ruby-on-rails ruby-on-rails-3

如果我有3个我想连接的模型怎么办?

例如:

用户可以为许多不同的应用程序拥有许多不同的权限.

所以我需要一个表来存储:

user_id
permission_id
application_id
Run Code Online (Sandbox Code Playgroud)

这可能与has_and_belongs_to_many有关吗?

谢谢

小智 5

我会用has_many来做:通过.

class Upa < ActiveRecord::Base
  belongs_to :user 
  belongs_to :permission 
  belongs_to :application
end
class User < ActiveRecord::Base
  has_many :permissions, :through => :upas
  has_many :applications, :through => :upas
end
class Permission < ActiveRecord::Base
  has_many :users, :through => :upas
  has_many :applications, :through => :upas
end
class Application < ActiveRecord::Base
  has_many :permissions, :through => :upas
  has_many :users, :through => :upas
end
Run Code Online (Sandbox Code Playgroud)

has_many的例子:通过

基本上,您可以在ActiveRecord中描述您可以使用关系数据库中的经典一对一,一对多和多对多关系描述的任何关系.