Search code examples
ruby-on-railsmodel-view-controllerruby-on-rails-5associations

Rails how to access users status on project level


I have two models User and Project which are in has_and_belongs_to_many association The user model has a column status i can access the status of a user who is in project like

project.user.status

but a user can be in different projects i want his status to be on project level instead of on his id


Solution

  • If I understand your question correctly, the problem is that you need to associate the status of the user to one of potentially many projects that the user is associated with, but you are associating a single status to a single user instead of the project.

    In that event, you need to abstract this association to an additional model, for instance "UserProjectStatus" which would be associated with both the User and the Project. You can do this using the has_many, through association. This would end up with something along the lines of:

    class Project < ApplicationRecord
      has_many :user_project_statuses
      has_many :users, through :user_project_statuses
    end
    
    class UserProjectStatus < ApplicationRecord
      belongs_to :user
      belongs_to :project
    end
    
    class User < ApplicationRecord
      has_many :user_project_statuses
      has_many :projects, through :user_project_statuses
    end
    

    There is a good overview of this any many other Rails ActiveModel associations at https://guides.rubyonrails.org/association_basics.html#the-has-one-through-association.

    Hope this helps!