Rails Cancancan - Doubt about table of Roles

Asked

Viewed 56 times

1

Good afternoon, I have the following models:

User.Rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  VALID_USERNAME_REGEX = /\A[a-zA-Z0-9]*[_|-|.]*[a-zA-Z0-9]*\z/
  VALID_EMAIL_REGEX = /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i

  validates :name, presence: true
  validates :username, presence: true,
        format: {with: VALID_USERNAME_REGEX,
                 message: "Somente letras, numeros e simbolos (. _ -)"}
  validates :email, presence: true,
        format: {with: VALID_EMAIL_REGEX}

  has_many :projects
  has_many :users_projects
  has_many :roles
  has_many :roles, through: :project
  has_many :shared_projects, through: :users_projects, source: :project
end

Project.Rb

class Project < ApplicationRecord
  belongs_to :user
  belongs_to :role

  has_many :users_projects
  has_many :collaborators, through: :users_projects, source: :user

  has_many :boards

  validates :name, presence: true
  #validates :user_id, presence: true
end

Role.Rb

class Role < ApplicationRecord
  has_many :projects
  has_many :users, through: :projects
end

User can have 3 different roles, Product Manager, Scrum Master and Developer. The problem is that, the role of a user depends on the project he is involved in, and the same user can be a Product Manager in one, and in another he can be a Developer for example. So the role of a user is more connected to a project than to the user himself. My question is, what’s the best way to put this together? The way I did, when I go popular my bank, I get an error saying that Role is mandatory. Could someone give me a hand?

1 answer

0

Felipe, I don’t know if I got it right, but I think I’d do something like this.

User

Role

Project
  has_many :project_users
  has_many :users, thought: :project_users

ProjectUser
  belongs_to :project
  belongs_to :user
  belongs_to :role

From what I understand the user can be connected to several projects with different roles.

There you can create a single validator for the scope.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.