0

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.

Gigi
  • 27
  • 1
  • 9
  • 3
    Models are not request aware. If you want to make it aware of the current user you need to pass it into the model. – max Sep 10 '20 at 10:32

2 Answers2

1

I had a similar question and was able to find a solution through the help of this question:

Rails validate uniqueness only if conditional

I think you can use the code below:

validate :need_price if user.admin?
Splohr
  • 67
  • 9
0

Your models should be valid regardless of whether the user which created them is currently logged in.

Start by adding a created_by association on your product model which records which user created it. Then you can validate that the creator is an admin, and perform conditional validation on other attributes based on the roles that user has.

Jon
  • 10,678
  • 2
  • 36
  • 48