【问题标题】:How to validate uniqueness of a field with a scope to enum value如何验证具有枚举值范围的字段的唯一性
【发布时间】:2019-10-10 07:45:53
【问题描述】:

我有一个消息表,它有一个枚举字段 type_of_message[:private, :public] 并且属于一个用户,我想验证一个用户只能发送一条公共消息。

validates_uniqueness_of :user, scope: :type_of_comment[:review]

【问题讨论】:

    标签: ruby-on-rails ruby validation scope


    【解决方案1】:

    你可以简单地使用:

    validates_uniqueness_of :user, scope: :type_of_message
    

    例如,如果您只想对特定 type_of_message 进行验证,我建议您为其编写自定义验证。

    validate :one_public_comment_per_user, on: :create
    
    private
    
    def one_public_comment_per_user
      if user.present? && user.messages.public.present?
        errors.add(:base, "only one public comment is allowed per user.")
      end
    end
    

    【讨论】:

    • 这假设桌子上有一个字段审查。
    【解决方案2】:

    我只是通过将评论作为字符串而不是符号传递来使其工作。 validates_uniqueness_of :user, scope: :type_of_comment['review']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多