Reputation: 31
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
Upvotes: 3
Views: 1106
Reputation: 174
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
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.
Upvotes: 4
Reputation: 316
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
Upvotes: 0