Home > Software engineering >  How to use CanCan in rails?
How to use CanCan in rails?

Time:02-28

I am working on a project called web portal for billboards management. My routes.rb looks like:

Rails.application.routes.draw do
  get "/", to: "main#index"

  get "/login", to: "login#loginpage"

  post "/login", to: "login#create"


  get "/register", to: "register#signup"

  post "/register",to: "register#create"

  get "/owner", to: "owner#ownerdashboard"

  get "/client", to: "client#clientdashboard"

  delete "/logout" , to: "login#destroy"

  get "/addbillboard", to: "addbillboard#add"

  post "/addbillboard", to: "addbillboard#addboard"

  get "/showboards", to: "showboards#showboards"

end

Currently i have only two models owner(for users details) and board(for billboards details). I have many controllers which are using these two models. Now i want to integrate cancan with my web app : specific users can access specific pages.My main problem is to prevent guests from accessing owner pages.Like only registered owner can add billboard. How can i ensure this? Looking forward for your answers.

CodePudding user response:

perhaps you should read first, i think it can be understanable

https://github.com/CanCanCommunity/cancancan

https://github.com/CanCanCommunity/cancancan/blob/develop/docs/README.md

there is Ability class you need to define

perhaps something like this

class Ability
  include CanCan::Ability

  def initialize(user)
    can :create, Billboard if owner?(user)
  end
  
  private def owner?(user)
   user.is_owner?
  end
end

the implementation is based on your context

  • Related