我正在开发一个现有用户可以邀请其他成员加入的 Rails 应用程序。这样做的问题是 User 模型存在于不同的状态,在这些不同的状态中,需要不同的信息集。
例如,John 是该站点的成员并邀请 Mary。 John 输入 Mary 的姓名和电子邮件地址,在数据库中为 Mary 创建一个用户记录,并发送一封邀请电子邮件。但是,在她加入后,所需的数据集会发生变化,我们要求她输入其他信息(例如密码)。
我仍在学习 Ruby on Rails,我看不到任何使用 validates_presence_of
的标准验证技术来处理这个问题的方法。 , validates_format_of
等任何人都可以指出我正确的方向
最佳答案
最简单的就是使用:if
如下:
class User < ActiveRecord::Base
validate_presence_of :name
validate_presence_of :age, :if => Proc.new { |user| user.signup_step >= 2 }
# ... etc
end
或者:
class User < ActiveRecord::Base
validate_presence_of :name
validate_presence_of :age, :if => :registering?
def registering?
signup_step >= 2
end
end
您也可以使用
validate
方法来定义任何复杂的自定义逻辑。例如:class User < ActiveRecord::Base
validate :has_name_and_email_after_invitation
validate :has_complete_profile_after_registration
def has_name_and_email_after_invitation
if ... # determine if we're creating an invitation
# step 1 validation logic here
end
end
def has_complete_profile_after_registration
if ... # determine if we're registering a new user
# step 2 validation logic here
end
end
end
(在上面的示例中,您实际上可以使用常规的
has_name_and_email_after_invitation
调用在 validates_xxx_of
中定义验证规则,因为它们也必须在步骤 2 中应用,但是对于单独的步骤使用两种方法可以为您提供最大的灵活性。)
关于ruby-on-rails - Rails 中的多状态验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/918428/