Ruby on Rails / Devise - Bypassing custom validation option in model when resetting password

前端 未结 3 1044
名媛妹妹
名媛妹妹 2021-02-06 05:00

In my project, I altered the registration form in Devise to add an :agree option via an accessor (user must accept terms of service to register, etc). If they don\'t agree, it d

相关标签:
3条回答
  • 2021-02-06 05:46

    I prefer to base these kinds of things on whether or not the record is new (which is the only time the user will be "signing up").

    class User < ActiveRecord::Base
      validates :agree, :term_agreement => TRUE, :if => :signing_up?
    
      # Return true if the user is currently signing up
      def signing_up?
        new_record?
      end
    end
    

    The key is to keep in mind that the value of :if and :unless is "a method, proc or string to call to determine if the validation should [or should not] occur"--so you're free to define methods on your model for this purpose.

    0 讨论(0)
  • 2021-02-06 05:49

    I fixed this by configuring devise to update the password attributes directing if validation failed, but only if the password attributes are error free.

    See my answer here:

    Validation errors are triggered when I'm trying to reset password

    0 讨论(0)
  • 2021-02-06 05:56

    So, you need to validate the acceptance of terms when the record is created?

    class User < ActiveRecord::Base
      validates :agree, :acceptance => true, :on => :create
    end
    

    :on => :create will only perform that validation when the record is being created—much like Brandon's answer, but without redundant code.

    This will also obviate the need for your controllers to worry about if a user is signed in or not.

    0 讨论(0)
提交回复
热议问题