【问题标题】:Using Rails' CanCan gem to handle a has_and_belongs_to_many situation使用 Rails 的 CanCan gem 处理 has_and_belongs_to_many 情况
【发布时间】:2011-07-26 05:49:02
【问题描述】:

我有以下几点:

  • has_and_belongs_to_many 餐厅的用户模型,反之亦然。
  • 餐厅模特that 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,但我还是不知道。

【问题讨论】:

    标签: ruby-on-rails has-and-belongs-to-many cancan


    【解决方案1】:

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

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

    【讨论】:

    • 整洁 - 感谢您的回复。我很快就会试试这个。出于好奇,这个 present?() 方法在哪里定义?它不在 Ruby Array 的文档中...
    • 很抱歉评论一个老问题。如果我在表格上执行:create 操作并且我正在勾选这顿饭属于哪些餐厅,我是否可以通过发送我拥有的 1 个餐厅 ID 和我拥有的 1 个餐厅 ID 来欺骗系统不是吗?上述条件将返回 true,因为存在一个正确的 ID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    相关资源
    最近更新 更多