能力:取决于对象的条件(允许:仅为team_members创建)

时间:2018-08-22 06:44:07

标签: ruby-on-rails authorization ruby-on-rails-5 cancan cancancan

设置

一种基本的酒店设置,其中Task 8 Task 8 | 15:47:32 | Preparing deployment: Preparing deployment (00:00:01) Task 8 | 15:47:33 | Preparing package compilation: Finding packages to compile (00:00:00) Task 8 | 15:47:33 | Compiling packages: nginx/d6ddf5c4782669341b260a27c53208d32a17b3a5 (00:00:10) L Error: CPI error 'Bosh::Clouds::VMCreationFailed' with message 'VM failed to create: googleapi: Error 403: Quota 'CPUS' exceeded. Limit: 8.0 in region europe-west3., quotaExceeded' in 'create_vm' CPI method Task 8 | 15:47:43 | Error: CPI error 'Bosh::Clouds::VMCreationFailed' with message 'VM failed to create: googleapi: Error 403: Quota 'CPUS' exceeded. Limit: 8.0 in region europe-west3., quotaExceeded' in 'create_vm' CPI method users的团队成员。它在Rails 5.2中使用cancancandevise

hotel

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连接到users。反之亦然,从has_many :users, through: :team_membershipsusers

config / routes.rb

hotels

app / controllers / check_ins_controller.rb

resources :hotels do
  resources :reservations
  resources :check_ins
end

app / models / ability.rb

class CheckInsController < ApplicationController
  before_action :authenticate_user!
  load_and_authorize_resource :hotel
  load_and_authorize_resource :check_in, :through => :hotel
[...]

问题/问题

在某个地方,我有以下代码:

[...]
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 URL应该不能供任何非团队成员使用。

1 个答案:

答案 0 :(得分:0)

尝试一下:

can [:create], CheckIn if user.team_memberships.present?

OR

can [:create], CheckIn if user.hotels.present?

希望这会有所帮助。