简体   繁体   English

选择模型的所有当前属性以在Rails中进行验证

[英]Selecting all current attributes of a model for validations in Rails

When setting up my models I often find myself having to write out all of its attributes when setting up certain validations. 设置模型时,我经常发现自己在设置某些验证时必须写出其所有属性。 A common example is when I use the presence parameter: 一个常见的例子是当我使用presence参数时:

validates :first_name, :last_name, :username, :email, presence: true

Is there a clever way to select all of its attributes without explicitly writing them all out similar to how you can retrieve them in the rails console? 有没有一种聪明的方法可以选择所有属性,而不必像在rails控制台中检索它们一样显式地全部写出它们?

User.columns

And pass it as an argument in the validates method? 并将其作为参数传递给validates方法?

ALL_ATTRIBUTES = User.columns

validates ALL_ATTRIBUTES, presence: true

Trying something like this out I got this error undefined method 'to_sym' 尝试这样的事情,我得到了这个错误undefined method 'to_sym'

I will NOT encourage you or anyone to do this. 我不会鼓励您或任何人这样做。 Reason being when you run into issues, when an object of your model doesn't get saved and throw errors because of a new column which was added to application after some time in future, and you or new developers will wonder WHY?!?!. 原因是当您遇到问题时,由于将来会在一段时间后将新列添加到应用程序中而导致无法保存模型对象并引发错误的情况,您或新开发人员会感到奇怪吗?!!! 。

However, if you must do then here you go: 但是,如果必须这样做,则可以执行以下操作:

validates *self.column_names.map(&:to_sym), presence: true

Here, * in Ruby is known as splat operator and here's the explanation on &: . 在这里,Ruby中的*被称为splat运算符这是对&:的解释

This is an awful idea. 这是一个可怕的主意。 But you can do it this way: 但是您可以通过以下方式进行操作:

attrs = column_names.map { |column| column.to_sym }
validates *attrs, presence: true

Why is it a bad idea? 为什么这是个坏主意? Because it's not very clear what is being validated it. 因为还不清楚正在验证什么。 It makes debugging hard, and could cause you have strange bugs. 它使调试变得困难,并可能导致您遇到奇怪的错误。 If you add a column in the future that does not require presence validation, you will trip up. 如果将来添加不需要进行状态验证的列,则会跳闸。 Also, some things my not require presence. 另外,有些事情我不需要出席。 For example, an email field will need a regex validation, which automatically knows that a blank string is invalid. 例如,电子邮件字段将需要正则表达式验证,该验证会自动知道空白字符串无效。 So a presence validator is redundant. 因此,状态验证器是多余的。

Beware of being too clever , as it's sometimes not so clever after all. 提防自己太聪明了 ,因为有时候毕竟不是那么聪明。

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

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