【发布时间】:2018-08-22 06:44:06
【问题描述】:
设置
一个基本的酒店设置,其中users 是hotel 的团队成员。它在 Rails 5.2 中使用 cancancan 和 devise
rails g scaffold User name
rails g scaffold Hotel name
rails g scaffold TeamMembership user:references hotel:references
rails g scaffold Reservation starts_on:date ends_on:date hotel:references
rails g scaffold CheckIn hotel:references reservation:references
hotels 通过has_many :users, through: :team_memberships 连接到users。反之亦然 users 到 hotels。
config/routes.rb
resources :hotels do
resources :reservations
resources :check_ins
end
app/controllers/check_ins_controller.rb
class CheckInsController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource :hotel
load_and_authorize_resource :check_in, :through => :hotel
[...]
app/models/ability.rb
[...]
can [:read, :destroy], CheckIn, hotel_id: user.hotel_ids
can [:create], CheckIn
[...]
问题/疑问
在某个视图中我有这个代码:
<% if can? :create, CheckIn %>
<%= link_to 'Create Check-In', new_hotel_check_in_path(@hotel) %>
<% end %>
它应该只对@hotel 的团队成员可见。
ability.rb 的第一行工作正常,但第二行不起作用,因为任何人都可以创建一个新的check_in,但只有team_memberships 应该能够为他们的酒店创建一个新的check_in .
解决此问题的最佳方法是什么?显然,该链接不应显示,但/hotels/:hotel_id/check_ins/new URL 应该不可供非团队成员的任何人访问。
【问题讨论】:
标签: ruby-on-rails authorization ruby-on-rails-5 cancan cancancan