I need to set a validation for some fields of Product model, but only if the current user as role admin. Product model is:
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
I would validate need_price only if product has been created by current_user and it is admin. But if I try to write:
if current_user.admin?
validate :need_price
end
I am not able to set the condition.