使用 Rails CanCan gem 处理 has_and_belongs_to_many 情况
我有以下内容:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“&”数组上的运算符将始终返回一个数组。空数组不被视为 false,因此它总是会通过。尝试检查它是否存在(不是空白)。
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).