Reputation: 3
I have three tables that look like this:
user -> id | nickname | email | pass
role -> id | name
user_roles -> id | user_id | role_id
I'm trying like that because one user could have a lot of roles I want to check roles like this: User.roles
.
Upvotes: 0
Views: 89
Reputation: 2436
This sounds like a classic use case for a has_many :through
association (docs here). Specifically:
class User < ApplicationRecord
has_many :user_roles
has_many :roles, through: :user_roles
end
class UserRole < ApplicationRecord
belongs_to :user
belongs_to :role
end
class Role < ApplicationRecord
has_many :user_roles
has_many :users, through: :user_roles
end
Upvotes: 2