开发者

Has and belongs to many with 3 Models

What if I had 3 Models that I wanted to connect.

For example:

A user can have many different permissions for many different applications.

开发者_运维百科

So I need a table to store:

user_id
permission_id
application_id

Is that possible with has_and_belongs_to_many?

Thanks


I would do it with a has_many :through.

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

examples of has_many :through

Basically any sort of relationship that you can describe with a classical one to one, one to many and many to many relationships in relational databases can be described in ActiveRecord.


Yes, you can have has_and_belongs_to_many relationship. More help can be found here http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜