Harakiri
Harakiri

Reputation: 730

Rails: Using CanCanCan Abilities to hide elements

I'm using the CanCanCan gem. According to the documentation you can define abilities. That is working for me. What I want to do is to limit the access to records, that contain a value. Something like:

can :crud, Order, :brand == empty?

A User should only be allowed to see the record, if the brand-column of the Order table is empty. As my example doesn't work apparently.. How would you do it?

Upvotes: 0

Views: 190

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

This is not the right use case for CanCanCan - it would be more appropriate to use a specific query in the SQL:

#app/models/order.rb
class Order < ActiveRecord::Base
   scope :no_brand, -> { where(brand: "") }
end

#app/controllers/orders_controller.rb
class OrdersController < ApplicationController
   def index
      @orders = Order.no_brand
   end
end

Of course, you could use CanCanCan, and to do it you'd do this:

#app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    can :read, Order, brand: ""
  end
end

The reason why I wouldn't do it is because CanCanCan is meant for authorization -- checking whether a user has permission to do something.

Your use case is best used with SQL query conditions.

Upvotes: 1

Related Questions