Rails中的多状态验证

Jas*_*son 7 validation ruby-on-rails

我正在开发一个Rails应用程序,现有用户可以邀请其他成员加入.这个问题是User模型存在于不同的状态,并且在那些不同的状态中,需要不同的信息集.

例如,John是该网站的成员并邀请Mary.John输入Mary的姓名和电子邮件地址,在Mary的数据库中创建用户记录,并发送邀请电子邮件.然而,在她加入之后,所需的数据集发生了变化,我们要求她输入其他信息(例如密码).

我还在学习Ruby on Rails的,我看不出有任何的方式来处理这个使用标准验证技术validates_presence_of,validates_format_of等等.任何人都可以点我在正确的方向

mol*_*olf 9

最简单的方法是使用:if如下:

class User < ActiveRecord::Base
  validate_presence_of :name
  validate_presence_of :age, :if => Proc.new { |user| user.signup_step >= 2 }
  # ... etc
end
Run Code Online (Sandbox Code Playgroud)

要么:

class User < ActiveRecord::Base
  validate_presence_of :name
  validate_presence_of :age, :if => :registering?

  def registering?
    signup_step >= 2
  end
end
Run Code Online (Sandbox Code Playgroud)

您还可以使用该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
Run Code Online (Sandbox Code Playgroud)

(在上面的示例中,您实际上可以has_name_and_email_after_invitation使用常规validates_xxx_of调用来定义验证规则,因为它们也必须在步骤2中应用,但是对于单独的步骤使用两种方法可以提供最大的灵活性.)


Mar*_*eri 5

而且,对于DRYin'up你的代码,你可以使用with_options,像这样:

class Example < ActiveRecord::Base
  [...]
  def registering?
    signup_step >= 2
  end
  with_options(:if => :registering?) do |c|
    c.validates_presence_of :name
  end

  with_options(:unless => :registering?) do |c|
    c.validates_presence_of :contact_details
  end
  [...]
end
Run Code Online (Sandbox Code Playgroud)

with_options在此处了解更多信息:

http://apidock.com/rails/v2.3.2/Object/with_options

甚至还有RailsCasts的截屏视频:

http://railscasts.com/episodes/42-with-options