以活动管理员嵌套形式验证 id 对的唯一性



我正在使用Activadmin嵌套表单,并具有以下模型结构:

货币.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

产品.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

产品货币.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 中使用嵌套表单(我可以为货币添加几个价格(。我怎么能确定用户无法为一种货币创建多个价格?谢谢。

不幸的是,我没有足够的观点来评论,即使这作为评论会更有帮助。

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

但是,validates_associated往往会在nested_associations中引起一些问题,因为在创建product_currency模型时product_id不存在。这将为您提供验证错误 -Product Currency - Product must be present

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

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

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

最新更新