get validations from model

[亡魂溺海] 提交于 2019-11-28 17:05:07

问题


How cat I get list of validations defined in model

Example:

class ModelName
  validates_presence_of :field_name
  validates_inclusion_of :sex, :in => %w(M F)
end

I need Hash like:

{:field_name => 'required', :sex => 'Must be in: M, F'}

回答1:


You don't need a plugin for basic needs.

You can do this to get a hash of all validators.

ModelName.validators

If you want to get the validators for a specific field :

ModelName.validators_on(:attribute)



回答2:


This code yields an array of required fields. It should be adaptable to your needs.

@required_fields = []
  ModelName.validators.each do |v|
  @required_fields << v.attributes.first if v.kind == :presence
end



回答3:


Looks like there's no native way to do it, but a quick Google (for "rails reflect validations") turns up this plugin.




回答4:


If you add validations dynamically in your models, you can use the instance to list the validations:

product = Product.new
product.singleton_class.validators_on(:price)
#=> [#<ActiveModel::Validations::PresenceValidaton>]

Tested in Rails 5.2.



来源:https://stackoverflow.com/questions/4051864/get-validations-from-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!