如何在 Rails 中使用 CanCan?

发布于 2025-01-10 09:53:09 字数 738 浏览 0 评论 0原文

我正在开发一个名为广告牌管理门户网站的项目。 我的routes.rb看起来像:

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

目前我只有两个模型所有者(用于用户详细信息)和板(用于广告牌详细信息)。我有很多控制器正在使用这两种模型。现在我想将 cancan 与我的网络应用程序集成:特定用户可以访问特定页面。我的主要问题是防止客人访问所有者页面。就像只有注册所有者才能添加广告牌一样。 我怎样才能确保这一点? 期待您的答复。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清泪尽 2025-01-17 09:53:09

也许你应该先阅读,我认为这是可以理解的

https://github.com/CanCanCommunity/cancancan

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

您需要定义 Ability

,也许这样的

class Ability
  include CanCan::Ability

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

实现是根据您的具体情况

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文