GavinBelson
GavinBelson

Reputation: 2794

Pundit Authorize From Another Model

I need to authorize a project based on invites that a supplier has gotten. Supplier has a "user_id" field.

project.rb

has_many :invites
has_many :suppliers, :through => :invites

project_policy.rb

class ProjectPolicy < ApplicationPolicy
  attr_reader :user, :project

  def initialize(user, project)
    @user = user
    @project = project
  end

  def show?
    ##need help on the next line##
    if project.joins(:invites).joins(:suppliers).pluck("suppliers.user_id") == user.id
      return true
    else
      return false
    end
  end
end

How can I show only the appropriate projects based on the user_id in the suppliers table? If this needs to be in the scope, then how do I check the suppliers.user_id in the scope?

Upvotes: 1

Views: 636

Answers (1)

fabOnReact
fabOnReact

Reputation: 5942

How can I show only the appropriate projects based on the user_id in the suppliers table?

The has_many :through Association

Invites.rb
  belongs_to :supplier
  belongs_to :project

Project model has many suppliers

Project.rb
  has_many :invites
  has_many :suppliers, :through => :invites

Supplier model has many projects

Supplier.rb
  has_many :invites
  has_many :projects, :through => :invites

Find the supplier and use the has_many :projects, :through => :invites

Supplier.find_by(user_id: user.id).projects

Upvotes: 2

Related Questions