Rails Cancancan定义3种关联的能力

问题描述 投票:0回答:1

使用Rails 6和CanCanCan。这是我的模特:

class Shop < ApplicationRecord
  has_many :shop_reviews, dependent: :destroy
end

class ShopReview < ApplicationRecord
  belongs_to :shop, counter_cache: true
  belongs_to :user_profile, counter_cache: true
end

class User < ApplicationRecord
  has_one :user_profile, dependent: :destroy
  has_many :shop_reviews, through: :user_profile
end

class UserProfile < ApplicationRecord
  belongs_to :user
  has_many :shop_reviews
end

ShopReview表:

id, shop_id, user_profile_id, review

协会:1.一家商店可以有很多评论2.商店中只有一个用户个人资料可以有一个评论

我想定义的能力:1.用户个人资料可以编辑,更新,销毁自己对商店的评论2.如果用户个人资料在该商店中已有评论,则不能创建新评论

我尝试过的事情:

class Ability
  include CanCan::Ability

  def initialize(user)
    can :read, :all
    if user.present?
      can [:update, :destroy], ShopReview, user_profile_id: user.user_profile.id
      can :create, ShopReview do
        !ShopReview.exists?(user_profile_id: user.user_profile.id, shop_id: :shop_id)
      end
    end
  end
end

但是我似乎无法通过shop_id访问/ shops / 11 / shop_reviews / new。这是日志:

Started GET "/shops/11/shop_reviews/new" for 127.0.0.1 at 2020-01-04 00:23:10 +0800
Processing by ShopReviewsController#new as HTML
  Parameters: {"shop_id"=>"11"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 9], ["LIMIT", 1]]
  UserProfile Load (0.2ms)  SELECT "user_profiles".* FROM "user_profiles" WHERE "user_profiles"."user_id" = $1 LIMIT $2  [["user_id", 9], ["LIMIT", 1]]
  ↳ app/models/ability.rb:9:in `initialize'
  ShopReview Exists? (0.3ms)  SELECT 1 AS one FROM "shop_reviews" WHERE "shop_reviews"."user_profile_id" = $1 AND "shop_reviews"."shop_id" = $2 LIMIT $3  [["user_profile_id", 8], ["shop_id", nil], ["LIMIT", 1]]
  ↳ app/models/ability.rb:11:in `block in initialize'
  Shop Load (0.2ms)  SELECT "shops".* FROM "shops" WHERE "shops"."id" = $1 ORDER BY "shops"."created_at" DESC LIMIT $2  [["id", 11], ["LIMIT", 1]]
ruby-on-rails cancancan
1个回答
0
投票

您应使用gem pundit在您的应用中创建授权。 Pundit比宝石cancancan更容易缩放。因为pundit允许您的应用在每个模型上创建授权。您可以搜索更多有关两种宝石的信息,然后选择最适合您的宝石。

© www.soinside.com 2019 - 2024. All rights reserved.