问题描述
我需要为产品模型的某些字段设置验证,但前提是当前用户为角色admin。 产品型号为:
class Product < ApplicationRecord
belongs_to :model
belongs_to :category
belongs_to :sub_category
belongs_to :cart_product,:optional => true
has_many :product_prices
accepts_nested_attributes_for :product_prices,:allow_destroy => true
has_many :product_features
has_many :features,:through => :product_features
accepts_nested_attributes_for :product_features
validate :need_price
validates :name,:model_id,:image,presence: true
validates :name,uniqueness: true
mount_uploader :image,ImageUploader
private
def need_price
if price.present?
errors.add(:price,'Il campo prezzo deve essere vuoto se hai impostato una fascia di prezzi.') if product_prices.present?
else
errors.add(:price,'Un campo tra prezzo o fascia di prezzi è obbligatorio.') if product_prices.empty?
end
end
end
仅当current_user创建了产品并且该产品为admin时,我才会验证 need_price 。 但是,如果我尝试写:
if current_user.admin?
validate :need_price
end
我无法设置条件。
解决方法
我有一个类似的问题,并且能够通过这个问题的帮助找到解决方案:
Rails validate uniqueness only if conditional
我认为您可以使用以下代码:
validate :need_price if user.admin?
,
您的模型应该有效,无论创建模型的用户当前是否登录。
首先在产品模型上添加一个created_by
关联,该关联会记录创建该用户的用户。然后,您可以验证创建者是管理员,然后根据用户所拥有的角色对其他属性执行条件验证。