Rails仅在有条件的情况下验证唯一性 [英] Rails validate uniqueness only if conditional

查看:94
本文介绍了Rails仅在有条件的情况下验证唯一性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Question类:

I have a Question class:

class Question < ActiveRecord::Base
  attr_accessible :user_id, :created_on

  validates_uniqueness_of :created_on, :scope => :user_id
end

一个给定的用户每天只能创建一个问题,因此我想通过唯一索引在数据库中强制唯一性,并通过validates_uniqueness_of强制在Question类中.

A given user can only create a single question per day, so I want to force uniqueness in the database via a unique index and the Question class via validates_uniqueness_of.

我遇到的麻烦是我只希望非管理员用户使用该约束.因此,管理员每天可以创建任意数量的问题.关于如何优雅地实现这一目标的任何想法?

The trouble I'm running into is that I only want that constraint for non-admin users. So admins can create as many questions per day as they want. Any ideas for how to achieve that elegantly?

推荐答案

您可以通过传递要执行的简单Ruby字符串,Proc或方法名称作为符号作为值传递给任一条件,从而使验证有条件验证选项中的:if:unless.以下是一些示例:

You can make a validation conditional by passing either a simple string of Ruby to be executed, a Proc, or a method name as a symbol as a value to either :if or :unless in the options for your validation. Here are some examples:

在Rails 5.2版之前,您可以传递一个字符串:

Prior to Rails version 5.2 you could pass a string:

# using a string:
validates :name, uniqueness: true, if: 'name.present?'

从5.2版开始,不再支持字符串,为您提供以下选择:

From 5.2 onwards, strings are no longer supported, leaving you the following options:

# using a Proc:
validates :email, presence: true, if: Proc.new { |user| user.approved? }

# using a Lambda (a type of proc ... and a good replacement for deprecated strings):
validates :email, presence: true, if: -> { name.present? }

# using a symbol to call a method:
validates :address, presence: true, if: :some_complex_condition

def some_complex_condition
  true # do your checking and return true or false
end

对于您而言,您可以执行以下操作:

In your case, you could do something like this:

class Question < ActiveRecord::Base
  attr_accessible :user_id, :created_on

  validates_uniqueness_of :created_on, :scope => :user_id, unless: Proc.new { |question| question.user.is_admin? }
end

有关详细信息,请查看rails指南中的条件验证"部分: http://edgeguides.rubyonrails.org/active_record_validations.html#conditional-validation

Have a look at the conditional validation section on the rails guides for more details: http://edgeguides.rubyonrails.org/active_record_validations.html#conditional-validation

这篇关于Rails仅在有条件的情况下验证唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆