是否可以在给定的 Controller 和操作上运行 ActiveRecord 验证。
例如我有 user_controller
和 signup_controller
我只需要在 signup_controller#create 操作上运行密码验证
最佳答案
您可以使用 if
运行验证有条件的:
validates :email, presence: true, if: :validate_email?
现在你需要定义这个实例方法(在你的模型中):
def validate_email?
validate_email == 'true' || validate_email == true
end
此
validate_email
属性可能是模型中的虚拟属性:attr_accessor :validate_email
现在,您可以根据该虚拟属性执行电子邮件验证。例如,在
signup_controller#create
您可以执行以下操作:def create
...
@user.validate_email = true
@user.save
...
end
关于ruby-on-rails - rails ActiveRecord 对特定 Controller 和 Action 的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22914257/