[英]Rails multiple conditional validation
I have the following model 我有以下型号
class User < ActiveRecord::Base
VALID_EMAIL_REGEX = /^.+@.+\..+$/i
attr_accessible :active_list_id, :password, :password_confirmation, :email, :temp
has_secure_password
before_create { generate_token(:auth_token) }
if :temp.nil?
before_validation :downcase_email
validates_presence_of :email, :password, :password_confirmation, :on => :create
validates_confirmation_of :password
#something@something.something
validates :email, :uniqueness => true,
:format => {:with => VALID_EMAIL_REGEX }
end
after_create { make_list([email,"'s shopping list"].join('')) }
has_many :shopping_lists
has_many :transactions, :class_name => 'Order'
HUMANIZED_ATTRIBUTES = {
:password_digest => "Password"
}
...
end
I try to create a model in my rails console by calling User.create(:temp => true)
(which is a boolean and is defined in my migrations/schema). 我试图通过调用User.create(:temp => true)
(这是一个布尔值,在我的迁移/方案中定义)在Rails控制台中创建模型。 But it always rollsback the transaction. 但是它总是回滚事务。 What am I doing wrong? 我究竟做错了什么?
I also tried doing :if => temp.nil?
我也尝试过:if => temp.nil?
and if => "temp.nil?"
if => "temp.nil?"
and :if => lambda { |user| user.temp.nil? }
和:if => lambda { |user| user.temp.nil? }
:if => lambda { |user| user.temp.nil? }
:if => lambda { |user| user.temp.nil? }
for all 3 of my validations. :if => lambda { |user| user.temp.nil? }
进行所有3次验证。
create a method called temp_is_nil? 创建一个名为temp_is_nil的方法? and use that on the if condition 并在if条件下使用
def temp_is_nil?
temp.nil?
end
make sure that temp is an attribute of user. 确保temp是用户的属性。
before_validation :downcase_email, if: temp_is_nil?
validates_presence_of :email, :password, :password_confirmation, :on => :create, if: temp_is_nil?
validates_confirmation_of :password, if: temp_is_nil?
validates :email, :uniqueness => true,
:format => {:with => VALID_EMAIL_REGEX }, if: temp_is_nil?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.