验证activeadmin嵌套表单中id对的唯一性

时间:2017-08-22 11:22:38

标签: ruby-on-rails validation activeadmin

我使用Activadmin嵌套表单,并拥有此模型结构:

Currency.rb

class Currency < ApplicationRecord
  has_many :product_currencies, dependent: :destroy
  has_many :products, through: :product_currencies
  has_many :variant_currencies
  has_many :variants, through: :variant_currencies

  validates :name, presence: true,
                   length: { minimum: 4 },
                   uniqueness: true
  validates :iso, presence: true,
                  length: { minimum: 2 },
                  uniqueness: true
end

Product.rb

class Product < ApplicationRecord
  belongs_to :category
  has_many :variants
  has_many :product_currencies
  has_many :currencies, through: :product_currencies
  accepts_nested_attributes_for :product_currencies, allow_destroy: true
  accepts_nested_attributes_for :variants, allow_destroy: true, reject_if: :all_blank
  mount_uploader :image, ProductImageUploader

  validates :name, presence: true,
                   length: { minimum: 5 },
                   uniqueness: true
  validates :category, presence: true
  validates :description, presence: true,
                          length: { minimum: 150 }
  validates :short_description, presence: true,
                                length: { in: 15..50 }
  validates :image, presence: true
  validates :subtitle, presence: true, length: { minimum: 5 }
end

ProductCurrency.rb

class ProductCurrency < ApplicationRecord
  belongs_to :product
  belongs_to :currency

  validates :currency, presence: true,
                       uniqueness: { scope: :product }
  validates :price, presence: true,
                    numericality: { greater_than_or_equal_to: 0.01 }

end

我希望product_idcurrecny_id的组合是唯一的。最后一个模型中唯一性的验证应该成为诀窍,但它只能在编辑时,而不是在创建时,因为在Activeadmin中使用嵌套表单(我可以为货币添加几个价格)。我怎么能确定,用户无法为一种货币创建多个价格?谢谢。

2 个答案:

答案 0 :(得分:0)

不幸的是,我没有足够的评论意见,尽管这可以作为评论更有帮助。

您的答案可能在于validates_associated,它可以帮助您添加相关元素的验证。 validates_associated :product_currencies

但是,validates_associated往往会导致嵌套关联中出现一些问题,因为在product_id模型创建时product_currency不会出现问题。这会给你一个验证错误 - Product Currency - Product must be present

该问题的解决方案是在您的关联中定义:inverse_of。希望它有所帮助。

答案 1 :(得分:0)

执行此操作的强力方法是在控制器中添加其他检查:

controller do
  def create
    if extra_validation(params)
      create!
    else
      redirect_to({action: :new}, {alert: ...})
    end
  end
end