简体   繁体   English

获取 Rails 的验证 model

[英]Get validations of a Rails model

Given a model that has validations in the model_name.rb file, how can I access those validations manually?鉴于 model 在 model_name.rb 文件中有验证,我如何手动访问这些验证? I'd like to cook up my own form validation system that would work alongside the built-in Rails tricks and I want to keep everything as DRY as possible.我想构建我自己的表单验证系统,它可以与内置的 Rails 技巧一起工作,并且我希望尽可能保持一切干燥。 My main problem is that I need to make server-side validations before any of the form values hit the database (I'm using a multistep form).我的主要问题是我需要在任何表单值进入数据库之前进行服务器端验证(我使用的是多步骤表单)。

Basically I'm wondering if there is a method like基本上我想知道是否有类似的方法

User.validations.each do |v|
    puts v.constraint.to_s + " " + v.message
end

Is there anything similar to this?有没有类似的东西?

Thanks in advance.提前致谢。

My main problem is that I need to make server-side validations before any of the form values hit the database (I'm using a multistep form).我的主要问题是我需要在任何表单值进入数据库之前进行服务器端验证(我使用的是多步骤表单)。

If your model is not valid according to the validations in its class file, then its data won't get saved to the database (unless you pass false to the save method to suppress validations).如果您的 model 根据其 class 文件中的验证无效,则其数据将不会保存到数据库中(除非您将false传递给save方法以抑制验证)。

  • You can ask a model if it's valid at any point by invoking its valid?您可以随时通过调用valid? / invalid? / invalid? methods.方法。

The ActiveRecord object exposes the errors method after valid? ActiveRecord object 在有效后公开错误方法? is called, which gives you messages about which validations are violated.被调用,它会向您提供有关违反了哪些验证的消息。 You could check valid?你可以检查有效吗? and then check to see if any of the fields on the part of the form you are on are invalid.然后检查您所在的表单部分是否有任何字段无效。 you could do something like this for a form with fields field1 and field2.您可以对具有字段 field1 和 field2 的表单执行类似的操作。

unless x.valid?
  [:field1,:field2].each do |field|
    yes_there_was_an_error if x.errors[field]
  end
end

Your best bet is to use a state machine and store the data in the database between the various steps in the form.最好的办法是使用 state 机器,并将数据存储在表单中各个步骤之间的数据库中。

You can do eg validates_presence_of:username, :if => proc {|u| u.signup_step >= 2 }你可以这样做,例如validates_presence_of:username, :if => proc {|u| u.signup_step >= 2 } validates_presence_of:username, :if => proc {|u| u.signup_step >= 2 } , where signup_step is an integer column in the database. validates_presence_of:username, :if => proc {|u| u.signup_step >= 2 } ,其中signup_step是数据库中的 integer 列。

So, even though you say you don't want to store it in the database between the forms, I think you should.所以,即使你说你不想将它存储在 forms 之间的数据库中,我认为你应该这样做。 If you do this, you can use regular validations and models, without nasty hacks.如果这样做,您可以使用常规验证和模型,而无需讨厌的黑客攻击。 And honestly, I doubt doing it this way is a problem.老实说,我怀疑这样做是不是有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM