Tyler DeWitt
Tyler DeWitt

Reputation: 23576

Use CanCan to limit specific parameters

Can CanCan be used to limit which parameterized views a user can access?

We produce images that users buy individual access to.

For instance:

Bob has access to images 1, 3, and 4. Joe has access to images 2 and 4. Steve has access to image 5.

The url would be something like site.com/images/1.

Is there a way I can restrict which number (parameter) of a view a user can view? With or without CanCan?

I'm using Rails 3.2.1

Thanks

Upvotes: 1

Views: 368

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

Here's an example from one of my projects.

classes

class App
  has_many :app_ownerships
end

class User
  has_many :app_ownerships
end

class AppOwnership
  belongs_to :user
  belongs_to :app


end

somewhere in ability.rb

can :read, App do |app|
  # find all ownerships with at least read-only access (access_level == 1)
  active = app.app_ownerships.select do |o|
    o.app_id == app.id && o.user_id == user.id && o.access_level >= 1
  end
  active.length > 0
end

somewhere in app_controller.rb

def show
  @app = App.find params[:id]
  authorize! :show, @app # throws exception if not authorized

  ...
end

Hope you can use this snippet for your needs.

Upvotes: 1

Related Questions