ruby-on-railsdatecancan

Is it possible to condition CanCan abilities on a date attribute range?


Given a Rails model "Widget" with an attribute "date", is it possible to place a condition on a CanCan action authorization that requires the date to be later than the current time? The documentation shows how to specify a range for a numeric attribute:

can :read, Project, :priority => 1..3

... but it's not clear how this would apply to an open-ended range for another type (e.g. "> Time.now"):

can :some_action, Widget, :date => "????"

Solution

  • You can define a block for conditions

    can :some_action, Widget do |widget|
      widget.date.to_time > Time.now
    end
    

    If the block returns true then the user has that ability, otherwise he will be denied access.

    Refer this for more info