Rails validate uniqueness only if conditional

后端 未结 3 730
Happy的楠姐
Happy的楠姐 2020-12-03 02:56

I have a Question class:

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

  validates_uniqueness_of :created_on, :scope =>          


        
3条回答
  •  失恋的感觉
    2020-12-03 03:09

    The only way I know of to guarantee uniqueness is through the database (e.g. a unique index). All Rails-only based approaches involve race conditions. Given your constraints, I would think the easiest thing would be to establish a separate, uniquely indexed column containing a combination of the day and user id which you'd leave null for admins.

    As for validates_uniqueness_of, you can restrict validation to non-admins through use of an if or unless option, as discussed in http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

提交回复
热议问题