Ruby on rails 确定权威的正确范围联接
我目前正在实现pundit,我试图确定用户是否具有管理员角色 问题 我试图通过利用折扣和用户之间的关系,避免在折扣和用户之间创建联接表Ruby on rails 确定权威的正确范围联接,ruby-on-rails,activerecord,pundit,Ruby On Rails,Activerecord,Pundit,我目前正在实现pundit,我试图确定用户是否具有管理员角色 问题 我试图通过利用折扣和用户之间的关系,避免在折扣和用户之间创建联接表 折扣和吸引力(折扣属于吸引力) 景点和公园(一个公园有很多景点) 公园和用户(多对多关系,通过join_表) -->但是,我得到了错误消息:未定义的局部变量或# 问题 我想知道: 如果可能的话,我想做什么,如果可能的话 我将如何访问该用户 代码 折扣控制器 def index @user = current_user if params[:a
- 折扣和吸引力(折扣属于吸引力)
- 景点和公园(一个公园有很多景点)
- 公园和用户(多对多关系,通过join_表)李>
未定义的局部变量或#
问题
我想知道:
def index
@user = current_user
if params[:attraction_id]
@attraction = Attraction.find(params[:attraction_id])
@discounts = @attraction.discounts
@discounts = policy_scope(@discounts)
else
@discounts = []
end
end
折扣政策
class DiscountPolicy < ApplicationPolicy
class Scope < Scope
def resolve
if user.admin?
# scope.where(user: user)
scope.joins(attraction: :discounts).where(discounts: { attraction_id: attraction.id }).joins(park: :attractions).where(attractions: { park_id: park.id }).joins(park: :user_parks).where(user_parks: { user_id: user.id })
else
raise Pundit::NotAuthorizedError
end
end
end
def index?
user.admin?
end
end
class折扣策略
模型
class Discount < ApplicationRecord
belongs_to :attraction
has_many :reservations
end
class Attraction < ApplicationRecord
belongs_to :park
has_many :discounts, dependent: :destroy
accepts_nested_attributes_for :discounts, allow_destroy: true
end
class Park < ApplicationRecord
has_many :attractions, dependent: :destroy
has_many :discounts, through: :attractions
has_many :user_parks, dependent: :destroy
has_many :users, through: :user_parks
accepts_nested_attributes_for :users, allow_destroy: true, reject_if: ->(attrs) { attrs['email'].blank? || attrs['role'].blank?}
end
class UserPark < ApplicationRecord
belongs_to :park
belongs_to :user
end
class User < ApplicationRecord
has_many :user_parks, dependent: :destroy
has_many :parks, through: :user_parks
enum role: [:owner, :admin, :employee, :accountant]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :admin
end
devise :invitable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :invitable
end
class折扣(attrs){attrs['email'].blank?| | attrs['role'].blank?}
终止
类UserPark:新建记录?
def set_默认_角色
self.role | |=:admin
终止
设计:不可修改,:数据库\可验证,:可注册,
:可恢复,:可记忆,:可验证,:不可侵犯
终止
您需要嵌套关联联接。以下是您的范围应该是什么样子:
scope.joins(attraction: [park: :user_parks]).where(user_parks: { user_id: user.id })
您可以浏览以更好地理解。非常感谢您,尤其是与相关文档的链接!