0

If I only want to return Proposals that are published but not expired, is this possible with Pundit?

So far, I have this:

class ProposalPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      if @user.admin?
        scope.all
      else
        scope.where(published: true)
      end
    end
  end

  ...

end

One work around is to write extra code in the index action of my Proposal controller to further filter the list of Proposals instances down to non-expired proposals.

I am hoping there's some magical syntax like this:

scope.where({published: true, expire_date > Time.now })

Any ideas? :D

Zhang
  • 11,549
  • 7
  • 57
  • 87

2 Answers2

2

You can either do this in a single where command:

scope.where('published = ? AND expire_date > ?', true, Time.now)

Or, split into two:

scope.where(published: true)
     .where('expire_date > ?', Time.now)

As for where this logic should go, that's up to you.

If it's really a restriction of the policy (i.e. only admins are allowed to see expired/unpublished proposals), then put it in the Pundit scope.

On the other hand, if non-admins are just being shown a filtered list for convenience (but can still view expired/unpublished proposals by some other means), then I'd rather put this query in the controller.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
  • Yes, seems like I didn't google hard enough, I found this page: https://stackoverflow.com/questions/8457902/how-to-specify-a-less-than-today-condition-on-a-date-in-rails-active-record Seems like scope.where() iterates over ActiveRecord relation, so the syntax is whatever ActiveRecord relation is (I used to think it's some black box with no documentation :D) – Zhang May 29 '17 at 11:56
  • No documentation??!!!! http://guides.rubyonrails.org/active_record_querying.html Rails is extremely well documented. – Tom Lord May 29 '17 at 12:01
  • Yes, I am enlightened now. I wasn't aware Pundit's `scope.where` is actually ActiveRecord relation, so the whole time I was scratching my head and checking Pundit's Github page to see extra documentation regarding multiple clause. On the Pundit Github page, it's one single bullet point, one could easily miss it :P – Zhang May 29 '17 at 12:07
1

Actually there is, you can do

scope .where(published: true) .where("expire_date > ? ",Time.now)

yorodm
  • 4,359
  • 24
  • 32
  • Had to give Tom Lord the tick for extra explanation regarding architecture of the system. Thank you for the answer nonetheless, wish I could double up vote you :D – Zhang May 29 '17 at 11:59