1

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?

GavinBelson
  • 2,514
  • 25
  • 36
  • Sorry. I don't understand your question. Is that like of code working? if now. What is the problem. Could you show us the result of the query – Fabrizio Bertoglio May 30 '17 at 06:14
  • Yeah, I have the model relationships set up, but trying to figure out what to put into the `show?` pundit policy so that it only allows access to projects that have an invite – GavinBelson May 31 '17 at 00:16

1 Answers1

2

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
Pang
  • 9,564
  • 146
  • 81
  • 122
Fabrizio Bertoglio
  • 5,890
  • 4
  • 16
  • 57