【发布时间】:2020-12-28 20:08:26
【问题描述】:
我需要为产品模型的某些字段设置验证,但前提是当前用户为角色管理员。 产品型号为:
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 创建并且它是管理员时,我才会验证 need_price。 但如果我尝试写:
if current_user.admin?
validate :need_price
end
我无法设置条件。
【问题讨论】:
-
模型不支持请求。如果你想让它知道当前用户,你需要将它传递给模型。
标签: ruby-on-rails validation model-view-controller model admin