使用 Rails CanCan gem 处理 has_and_belongs_to_many 情况

发布于 2024-11-26 11:24:54 字数 754 浏览 1 评论 0原文

我有以下内容:

  • has_and_belongs_to_many 餐厅的用户模型,反之亦然。
  • 餐厅模型has_and_belongs_to_many 餐食,反之亦然。

在我的ability.rb 文件中,我想指定用户只能管理他“has_and_belongs_to”的餐厅(即user.restaurants 中的餐厅)的餐点。

我现在有这个:

class Ability
  include CanCan::Ability
  def initialize(user)
    # a user can only manage meals of restaurants he has access to
    can :manage, Meal do |meal| 
      meal.restaurant_ids & user.restaurant_ids #...this doesn't work...
    end
  end
end

最好的方法是什么?

我咨询过 https://github.com/ryanb/cancan/wiki /Defining-Abilities-with-Blocks 但我还是不知道。

I have the following:

  • User model that has_and_belongs_to_many Restaurants and vice-versa.
  • Restaurant model that has_and_belongs_to_many Meals and vice-versa.

In my ability.rb file, I want to specify that a user can only manage meals of restaurants he "has_and_belongs_to" (i.e. restaurants in user.restaurants).

I have this right now:

class Ability
  include CanCan::Ability
  def initialize(user)
    # a user can only manage meals of restaurants he has access to
    can :manage, Meal do |meal| 
      meal.restaurant_ids & user.restaurant_ids #...this doesn't work...
    end
  end
end

What's the best way to do this?

I've consulted https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks but I still don't know.

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

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

发布评论

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

评论(1

风轻花落早 2024-12-03 11:24:54

“&”数组上的运算符将始终返回一个数组。空数组不被视为 false,因此它总是会通过。尝试检查它是否存在(不是空白)。

(meal.restaurant_ids & user.restaurant_ids).present?

The "&" operator on an array will always return an array. An empty array is not considered false, so it will always pass. Try checking if it is present (not blank).

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