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
精彩评论