简体   繁体   English

验证多态关联的唯一性

[英]validate uniqueness of polymorphic association

I'm trying to implement a validation for a polymorphic association, where I only want it to trigger on a certain type. 我正在尝试对多态关联进行验证,我只希望它在某种类型上触发。 Which is user. 哪个是用户。

I'd want something like this: 我想要这样的东西:

validates :room_id, uniqueness: { scope: tokenable_id if tokenable type is User }

how do I go about doing this. 我该怎么做。 The other type is Customer. 另一种类型是客户。 Which I want to allow the opportunity to be several. 我想允许有几个机会。

I think you can use Conditional Validation 我认为您可以使用条件验证

Sometimes it will make sense to validate an object only when a given predicate is satisfied. 有时,只有在满足给定谓词的情况下,才可以验证对象。 You can do that by using the :if and :unless options, which can take a symbol, a string, a Proc or an Array. 您可以使用:if和:unless选项来执行此操作,这些选项可以使用符号,字符串,Proc或Array。 You may use the :if option when you want to specify when the validation should happen. 要指定何时进行验证,可以使用:if选项。 If you want to specify when the validation should not happen, then you may use the :unless option. 如果要指定什么时候不应该进行验证,则可以使用:unless选项。

5.1 Using a Symbol with :if and :unless 5.1将符号与:if和:un一起使用

You can associate the :if and :unless options with a symbol corresponding to the name of a method that will get called right before validation happens. 您可以将:if和:unless选项与对应于方法名称的符号关联,该名称将在验证发生之前立即被调用。 This is the most commonly used option. 这是最常用的选项。

class Order < ActiveRecord::Base
  validates :room_id, uniqueness: { scope: :tokenable_id }, if: :is_right_type?

  # or maybe this will work
  validates :room_id, uniqueness: { scope: :tokenable_id }, if: :user?

  def is_right_type?
    type == "user"
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM