【问题标题】:Validation in model only if current_user is admin - Rails仅当 current_user 是管理员时才在模型中进行验证 - Rails
【发布时间】: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


【解决方案1】:

我有一个类似的问题,并且能够通过这个问题的帮助找到解决方案:

Rails validate uniqueness only if conditional

我认为你可以使用下面的代码:

validate :need_price if user.admin?

【讨论】:

    【解决方案2】:

    无论创建模型的用户当前是否登录,您的模型都应该是有效的。

    首先在您的产品模型上添加一个created_by 关联,以记录创建它的用户。然后您可以验证创建者是管理员,并根据用户拥有的角色对其他属性进行条件验证。

    【讨论】:

      猜你喜欢
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 2018-02-12
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多