gpt4 book ai didi

ruby-on-rails - Ruby on Rails 验证错误

转载 作者:数据小太阳 更新时间:2023-10-29 07:11:14 24 4
gpt4 key购买 nike

我已经设置了一个小应用程序来获取一个电子邮件地址并保存它,我已经在模型上设置了验证(唯一且有效的电子邮件)并且这些都有效。

我正在使用下面的代码来尝试保存电子邮件,如果它已经存在或者它不是有效的格式,它需要停止并设置错误消息

def create
interest = KnownInterest.new( :email => params[:email] )
if(interest.valid? and interest.save)
flash[:notice] = "Thanks for showing interest, We'll be in touch with updates."
else
flash[:notice] = interest.errors.messages
end
redirect_to action: "index"
end

这会吐出 ["Email not valid"],我怎么把它变成一个字符串(不是我认为的数组,如果我错了请纠正我)

最佳答案

如果您只想要第一条消息,那么 interest.errors.messages.first。如果你想要它们,那么类似 interest.errors.full_messages.join(", ") 的东西会将所有消息组合成一个字符串。

但是,您可能想要复习一下 ActiveRecord 验证和错误。
这是一个很好的指南:

http://guides.rubyonrails.org/active_record_validations_callbacks.html

至少阅读:

关于ruby-on-rails - Ruby on Rails 验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11273513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com