Search code examples
ruby-on-railspundit

Pundit Policies with Joins


I have churches that use songs.

With a specific song id I am trying to get the most recent usage date and the total of usages limited by whichever church the user belongs to.

@usages = Usage.select("MAX(services.date) as date", :song_name, :song_id, "count(song_id) as count_song_id").joins(:service, :song).where(:services => {church_id: current_user.church_id}).group(:song_name, :song_id).order("count_song_id DESC")

The above code seems to be working but I've now started implementing Pundit authorisation and have run into some difficulties. My scope policy is very simple:

class Scope < Scope
  def resolve
    if user.admin?
      scope.all
    else
      scope.where church_id: current_user.church_id
    end
  end
end

The problem is how to actually use it with joins. This doesn't seem right but I'm kind of at a loss:

@usages = policy_scope Usage.select("MAX(services.date) as date", :song_name, :song_id, "count(song_id) as count_song_id").joins(:service, :song).group(:song_name, :song_id).order("count_song_id DESC")

Solution

  • So what has ended up working (I think) is:

    @usages = policy_scope(Usage.joins :service)
      .select("MAX(services.date) as date", :song_name, :song_id, "count(song_id) as count_song_id")
      .joins(:service, :song)
      .group(:song_name, :song_id)
      .order("count_song_id DESC")
    

    The key being policy_scope(Usage.joins :service)