errors 对象
errors 是一个错误对象;
大概长这样
#<ActiveModel::Errors:0x007fe10b7d16a0 @base=#<User id: nil, name: nil, address: nil, age: nil, created_at: nil, updated_at: nil, home_page_urls: nil, terms_of_service: nil, email: nil, alisa_name: nil, role: nil, length_of_service: nil>, @messages={:name=>["名字不能为空", "名字只能是3-8位"], :alisa_name=>["别名只能为四位"], :email_confirmation=>["确认邮箱不能为空"], :email=>["必须输入邮箱格式", "%{value}不是一个邮箱"]}, @details={:name=>[{:error=>:blank}, {:error=>:too_short, :count=>3}], :alisa_name=>[{:error=>:wrong_length, :count=>4}], :email_confirmation=>[{:error=>:blank}], :email=>[{:error=>:invalid, :value=>nil}]}>
errors.messages 错误消息hash
1、键是 字段,每个字段的错误消息 是值
2、值装在数组中
大概这样
{
:name => [
[0] "名字不能为空",
[1] "名字只能是3-8位"
],
:alisa_name => [
[0] "别名只能为四位"
],
:email_confirmation => [
[0] "确认邮箱不能为空"
],
:email => [
[0] "必须输入邮箱格式",
[1] "%{value}不是一个邮箱"
]
}
errors.full_messages 将字段和错误信息组合
便于页面显示,它是一个数组
[
[0] "Name 名字不能为空",
[1] "Name 名字只能是3-8位",
[2] "Alisa name 别名只能为四位",
[3] "Email confirmation 确认邮箱不能为空",
[4] "Email 必须输入邮箱格式",
[5] "Email %{value}不是一个邮箱"
]
errors[:name] 取出单个字段的错误消息
image.png向errors中添加错误消息
1、
errors.add(:name,'message')
常用写法
2、errors[:name] << 'message'
和上等价
3、errors.messages[:name] << 'message'
等价
4、errors[:base] << 'message'
对于对象的错误信息,非字段装到base中
errors.clear 清空错误消息
errors.details查看错误键 hash
{
:name => [
[0] {
:error => :blank
},
[1] {
:error => :too_short,
:count => 3
}
],
:alisa_name => [
[0] {
:error => :wrong_length,
:count => 4
}
],
:email_confirmation => [
[0] {
:error => :blank
}
],
:email => [
[0] {
:error => :invalid,
:value => nil
}
]
}
网友评论