简体   繁体   English

自定义验证Rails模型

[英]Custom Validations Rails Model

I have a contact form and would like to show individual messages depending on what has failed.I would like to use flash messages. 我有一个联系表,想根据失败的原因显示个别消息。我想使用即时消息。 So from what i have read so far i can create a custom method (or i think it just overrides the one in place?) 因此,从我到目前为止所读的内容中,我可以创建一个自定义方法(或者我认为它会覆盖现有的方法?)

So for example, i want to validate the presence of the name field 因此,例如,我想验证名称字段的存在

Class Message

attr_accessor :name
validates :name, :presence => true

def validate
 if self.name < 0
  errors.add(:name, "Name cannot be blank")
 end
end
end

Within my controller i normally use a generic message 在我的控制器内,我通常使用通用消息

flash.now.alert = "Please Ensure all Fields are filled in"

Is there a way to call the particular message that failed validation? 有没有办法调用验证失败的特定消息?

Thanks 谢谢

有可用的插件,您可以按照以下网址进行操作

https://github.com/jeremydurham/custom-err-msg

检查方法是否有效,因为您可以传递带有所需消息的message参数。

validates :name, :presence => {:message => 'The name can't be blank.'}

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

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