Rails CanCanCan - Questions about Roles table

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

The 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 to which he is involved, the same user can be Product Manager in one, and another can be Developer for example. Thus, the role of a user is more connected to a project than to the user. My question is, what is the best way to put this together? The way I did it, when I go popular my bank, I get an error saying that Role is required. Could someone give me a hand?

    
asked by anonymous 18.05.2018 / 20:41

1 answer

0

Felipe, I do not know if I understood correctly, but I think I would 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

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

Then you can create a unique validator for the scope.

    
04.07.2018 / 06:04