- 浏览: 2072565 次
- 性别:
- 来自: NYC
文章分类
- 全部博客 (628)
- Linux (53)
- RubyOnRails (294)
- HTML (8)
- 手册指南 (5)
- Mysql (14)
- PHP (3)
- Rails 汇总 (13)
- 读书 (22)
- plugin 插件介绍与应用 (12)
- Flex (2)
- Ruby技巧 (7)
- Gem包介绍 (1)
- javascript Jquery ext prototype (21)
- IT生活 (6)
- 小工具 (4)
- PHP 部署 drupal (1)
- javascript Jquery sort plugin 插件 (2)
- iphone siri ios (1)
- Ruby On Rails (106)
- 编程概念 (1)
- Unit Test (4)
- Ruby 1.9 (24)
- rake (1)
- Postgresql (6)
- ruby (5)
- respond_to? (1)
- method_missing (1)
- git (8)
- Rspec (1)
- ios (1)
- jquery (1)
- Sinatra (1)
最新评论
-
dadadada2x:
user模型里加上 protected def email ...
流行的权限管理 gem devise的定制 -
Sev7en_jun:
shrekting 写道var pattern = /^(0| ...
强悍的ip格式 正则表达式验证 -
jiasanshou:
好文章!!!
RPM包rpmbuild SPEC文件深度说明 -
寻得乐中乐:
link_to其实就是个a标签,使用css控制,添加一个参数: ...
Rails在link_to中加参数 -
aiafei0001:
完全看不懂,不知所然.能表达清楚一点?
"$ is not defined" 的问题怎么办
两个参考:
http://dizzy.co.uk/ruby_on_rails/cheatsheets/active-record-validation-errors
API:http://api.rubyonrails.org/classes/ActiveRecord/Errors.html
http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
1. Read methods
1.1. []
Alias for on method.
1.2. count
Alias for size
1.3. each
Yields each attribute attr and associated message msg per error added.
1.4. each_full
Yields each full error message msg added. So Person.errors.add("first_name", "can't be empty") will be returned through iteration as "First name can't be empty".
1.5. full_messages
Returns all the full error messages in an array.
1.6. empty?
Returns true if no errors have been added.
1.7. length
Alias for size
1.8. on
Returns nil, if no errors are associated with the specified attribute. Returns the error message if one error is associated with the specified attribute. Returns an array of error messages if more than one error is associated with the specified attribute.
This method is also aliased as the shortcut []
1.9. on_base
Returns errors that have been assigned to the base object through add_to_base according to the normal rules of on(:attribute).
1.10. invalid?
Returns true if the specified attribute has errors associated with it.
1.11. size
Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
1.12. to_xml
Returns an XML representation of this error object.
2. Write methods
2.1. add
Adds an error message msg to the attribute, which will be returned on a call to on(attribute) for the same attribute and ensure that this error object returns false when asked if empty?. More than one error can be added to the same attribute in which case an array will be returned on a call to on(attribute). If no msg is supplied, "invalid" is assumed.
2.2. add_on_blank
Will add an error message to each of the attributes in [attributes] that is blank (for example, an empty string).
2.3. add_on_empty
Will add an error message to each of the attributes in attributes that is empty.
2.4. add_to_base
Adds an error, msg, to the base object instead of any particular attribute. This is used to report errors that don’t tie to any specific attribute, but rather to the object as a whole. These error messages don’t get prepended with any field name when iterating with each_full, so they should be complete sentences.
2.5. clear
Removes all the errors that have been added to the object.
3. Default error messages
These error messages are stored in a Rails class variable, @@default_error_messages and can be changed or added to as follows:
These default error messages are used by Rails’ built in validation class methods and some of the errors object’s write methods such as add_on_blank. You may find it useful to change them if, for example, you require your error messages in a different language.
4.1. error_message_on
Returns a string containing the error message attached to the attribute of the object if one exists. This error message is wrapped in a <div> tag, which can be extended to include a prepend_text and/or append_text (to properly explain the error), and a css_class to style it accordingly. Object should either be the name of an instance variable or the actual object itself. As an example, let’s say you have a model @post that has an error message on the title attribute…
4.1.1. Options
4.2. error_messages_for
Returns a string with a <div> containing all of the error messages for the objects located as instance variables by the names given. If more than one object is specified, the errors for the objects are displayed in the order that the object names are provided.
This <div> can be tailored by the following options…
4.2.1. Options
To specify the display for one object, you simply provide its name as a parameter. For example, for the @user model…
To specify more than one object, you simply list them: optionally, you can add an extra object_name parameter, which will be the name used in the header message:
If the objects cannot be located as instance variables, you can add an extra object parameter which gives the actual object (or aarray of objects to use)…
This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what you need is significantly different from the default presentation, it makes plenty of sense to access the object.errors instance yourself and set it up.
http://dizzy.co.uk/ruby_on_rails/cheatsheets/active-record-validation-errors
API:http://api.rubyonrails.org/classes/ActiveRecord/Errors.html
http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
1. Read methods
1.1. []
object.errors[:attribute]
Alias for on method.
1.2. count
Alias for size
1.3. each
each { |attr, msg| ... }
Yields each attribute attr and associated message msg per error added.
class Company < ActiveRecord::Base validates_presence_of :name, :address, :email validates_length_of :name, :in => 5..30 end company = Company.create(:address => '123 First St.') company.errors.each { |attr,msg| puts "#{attr} - #{msg}" } # => name - is too short (minimum is 5 characters) # => name - can't be blank # => email - can't be blank
1.4. each_full
each_full {|msg| ...}
Yields each full error message msg added. So Person.errors.add("first_name", "can't be empty") will be returned through iteration as "First name can't be empty".
class Company < ActiveRecord::Base validates_presence_of :name, :address, :email validates_length_of :name, :in => 5..30 end company = Company.create(:address => '123 First St.') company.errors.each_full{|msg| puts msg } # => Name is too short (minimum is 5 characters) # => Name can't be blank # => Email can't be blank
1.5. full_messages
Returns all the full error messages in an array.
class Company < ActiveRecord::Base validates_presence_of :name, :address, :email validates_length_of :name, :in => 5..30 end company = Company.create(:address => '123 First St.') company.errors.full_messages # => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
1.6. empty?
Returns true if no errors have been added.
1.7. length
Alias for size
1.8. on
on(:attribute)
Returns nil, if no errors are associated with the specified attribute. Returns the error message if one error is associated with the specified attribute. Returns an array of error messages if more than one error is associated with the specified attribute.
class Company < ActiveRecord::Base validates_presence_of :name, :address, :email validates_length_of :name, :in => 5..30 end company = Company.create(:address => '123 First St.') company.errors.on(:name) # => ["is too short (minimum is 5 characters)", "can't be blank"] company.errors.on(:email) # => "can't be blank" company.errors.on(:address) # => nil
This method is also aliased as the shortcut []
1.9. on_base
Returns errors that have been assigned to the base object through add_to_base according to the normal rules of on(:attribute).
1.10. invalid?
Returns true if the specified attribute has errors associated with it.
class Company < ActiveRecord::Base validates_presence_of :name, :address, :email validates_length_of :name, :in => 5..30 end company = Company.create(:address => '123 First St.') company.errors.invalid?(:name) # => true company.errors.invalid?(:address) # => false
1.11. size
Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
1.12. to_xml
Returns an XML representation of this error object.
2. Write methods
2.1. add
add(attribute, msg = @@default_error_messages[:invalid])
Adds an error message msg to the attribute, which will be returned on a call to on(attribute) for the same attribute and ensure that this error object returns false when asked if empty?. More than one error can be added to the same attribute in which case an array will be returned on a call to on(attribute). If no msg is supplied, "invalid" is assumed.
2.2. add_on_blank
add(attribute, msg = @@default_error_messages[:blank])
Will add an error message to each of the attributes in [attributes] that is blank (for example, an empty string).
2.3. add_on_empty
add(attribute, msg = @@default_error_messages[:empty])
Will add an error message to each of the attributes in attributes that is empty.
add_on_empty(:name, :surname, :age, "empty is bad!")
2.4. add_to_base
add_to_base([attributes], msg = @@default_error_messages[:empty])
Adds an error, msg, to the base object instead of any particular attribute. This is used to report errors that don’t tie to any specific attribute, but rather to the object as a whole. These error messages don’t get prepended with any field name when iterating with each_full, so they should be complete sentences.
add_to_base(:name, :surname, :age, "default error message here")
2.5. clear
Removes all the errors that have been added to the object.
3. Default error messages
These error messages are stored in a Rails class variable, @@default_error_messages and can be changed or added to as follows:
ActiveRecord::Errors.default_error_messages[:blank] = "Your custom message here"
These default error messages are used by Rails’ built in validation class methods and some of the errors object’s write methods such as add_on_blank. You may find it useful to change them if, for example, you require your error messages in a different language.
引用
Key Value
:inclusion “is not included in the list”
:exclusion “is reserved”
:invalid “is invalid”
:confirmation “doesn’t match confirmation”
:accepted “must be accepted”
:empty “can’t be empty”
:blank “can’t be blank”
:too_long “is too long (maximum is %d characters)”
:too_short “is too short (maximum is %d characters)”
:wrong_length “is the wrong length (should be %d characters)”
:taken “has already been taken
:not_a_number “is not a number
:greater_than “must be greater than %d”
:greater_than_or_equal_to “must be greater than or equal to %d”
:equal_to “must be equal to %d”
:less_than “must be less than %d”
:less_than_or_equal_to “must be less than or equal to %d”
:odd “must be odd”
:even “must be even”
4. View Helpers
:inclusion “is not included in the list”
:exclusion “is reserved”
:invalid “is invalid”
:confirmation “doesn’t match confirmation”
:accepted “must be accepted”
:empty “can’t be empty”
:blank “can’t be blank”
:too_long “is too long (maximum is %d characters)”
:too_short “is too short (maximum is %d characters)”
:wrong_length “is the wrong length (should be %d characters)”
:taken “has already been taken
:not_a_number “is not a number
:greater_than “must be greater than %d”
:greater_than_or_equal_to “must be greater than or equal to %d”
:equal_to “must be equal to %d”
:less_than “must be less than %d”
:less_than_or_equal_to “must be less than or equal to %d”
:odd “must be odd”
:even “must be even”
4.1. error_message_on
error_message_on(object, attribute, prepend_text = "", append_text = "", css_class = "formError")
Returns a string containing the error message attached to the attribute of the object if one exists. This error message is wrapped in a <div> tag, which can be extended to include a prepend_text and/or append_text (to properly explain the error), and a css_class to style it accordingly. Object should either be the name of an instance variable or the actual object itself. As an example, let’s say you have a model @post that has an error message on the title attribute…
error_message_on "post", "title" # => <div class="formError">can't be empty</div> error_message_on @post, "title" # => <div class="formError">can't be empty</div> error_message_on "post", "title", "Title simply ", " (or it won't work).", "inputError" # => <div class="inputError">Title simply can't be empty (or it won't work).</div>
4.1.1. Options
4.2. error_messages_for
Returns a string with a <div> containing all of the error messages for the objects located as instance variables by the names given. If more than one object is specified, the errors for the objects are displayed in the order that the object names are provided.
This <div> can be tailored by the following options…
4.2.1. Options
引用
Option Type Value
:header_tag String Used for the header of the error <div> (default is h2)
:id String The class of the error <div> (default is errorExplanation)
:class String The id of the error <div> (default is errorExplanation)
object Object The object (or array of objects) for which to display errors, if you need to escape the instance variable convention
object_name String The object name to use in the header, or any text that you prefer. If object_name is not set, the name of the first object will be used
:header_message String The message in the header of the error <div>. Pass nil or an empty string to avoid the header message altogether (default message is "X errors prohibited this object from being saved")
:message String The explanation message after the header message and before the error list. Pass nil or an empty string to avoid the explanation message altogether (default message is "There were problems with the following fields:")
:header_tag String Used for the header of the error <div> (default is h2)
:id String The class of the error <div> (default is errorExplanation)
:class String The id of the error <div> (default is errorExplanation)
object Object The object (or array of objects) for which to display errors, if you need to escape the instance variable convention
object_name String The object name to use in the header, or any text that you prefer. If object_name is not set, the name of the first object will be used
:header_message String The message in the header of the error <div>. Pass nil or an empty string to avoid the header message altogether (default message is "X errors prohibited this object from being saved")
:message String The explanation message after the header message and before the error list. Pass nil or an empty string to avoid the explanation message altogether (default message is "There were problems with the following fields:")
To specify the display for one object, you simply provide its name as a parameter. For example, for the @user model…
error_messages_for :user
To specify more than one object, you simply list them: optionally, you can add an extra object_name parameter, which will be the name used in the header message:
error_messages_for :user_common, :user, :object_name => :user
If the objects cannot be located as instance variables, you can add an extra object parameter which gives the actual object (or aarray of objects to use)…
error_messages_for :user, :object => @question.user
This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what you need is significantly different from the default presentation, it makes plenty of sense to access the object.errors instance yourself and set it up.
发表评论
-
Destroying a Postgres DB on Heroku
2013-04-24 10:58 928heroku pg:reset DATABASE -
VIM ctags setup ack
2012-04-17 22:13 3255reference ctags --extra=+f --e ... -
alias_method_chain方法在3.1以后的替代使用方式
2012-02-04 02:14 3288alias_method_chain() 是rails里的一个 ... -
一些快速解决的问题
2012-01-19 12:35 1470问题如下: 引用Could not open library ... -
API service 安全问题
2011-12-04 08:47 1380这是一个长期关注的课题 rest api Service的 ... -
Module方法调用好不好
2011-11-20 01:58 1344以前说,用module给class加singleton方法,和 ... -
一个ajax和rails交互的例子
2011-11-19 01:53 1903首先,这里用了一个,query信息解析的包,如下 https: ... -
Rails 返回hash给javascript
2011-11-19 01:43 2272这是一个特别的,不太正统的需求, 因为,大部分时候,ajax的 ... -
关于Rubymine
2011-11-18 23:21 2263开个帖子收集有关使用上的问题 前一段时间,看到半价就买了。想 ... -
ruby中和javascript中,动态方法的创建
2011-11-18 21:01 1234class Klass def hello(*args) ... -
textmate快捷键 汇总
2011-11-16 07:20 8138TextMate 列编辑模式 按住 Alt 键,用鼠标选择要 ... -
Ruby面试系列六,面试继续面试
2011-11-15 05:55 2018刚才受到打击了,充分报漏了自己基础不扎实,不肯向虎炮等兄弟学习 ... -
说说sharding
2011-11-13 00:53 1481这个东西一面试就有人 ... -
rails面试碎碎念
2011-11-12 23:51 1939面试继续面试 又有问ru ... -
最通常的git push reject 和non-fast forward是因为
2011-11-12 23:29 17209git push To git@github.com:use ... -
Rails 自身的many to many关系 self has_many
2011-11-12 01:43 2732简单点的 #注意外键在person上people: id ... -
Rails 3下的 in place editor edit in place
2011-11-12 01:20 945第一个版本 http://code.google.com/p ... -
Heroku 的诡异问题集合
2011-11-11 07:22 1692开个Post记录,在用heroku过程中的一些诡异问题和要注意 ... -
SCSS 和 SASS 和 HAML 和CoffeeScript
2011-11-07 07:52 12952Asset Pipeline 提供了内建 ... -
Invalid gemspec because of the date format in specification
2011-11-07 02:14 2115又是这个date format的错误。 上次出错忘了,记录下 ...
相关推荐
在Ruby on Rails(Rails)框架中,验证码是一种用于防止恶意自动化的工具,它通常用于注册、登录和其他敏感操作,以确保只有人类...在实际开发中,还可以根据需求进行更多定制,例如添加错误提示、调整验证码难度等。
Simple Form能够自动处理模型验证错误,将错误信息显示在相应的输入字段下方。无需额外的代码,就能实现良好的用户体验。 5. **自定义样式和布局** Simple Form允许开发者灵活地定制表单的外观。可以设置`:...
9. 友好的错误提示:在用户进行操作时,RailsAdmin 能够提供清晰的错误信息,帮助快速定位问题。 在实际项目中,使用RailsAdmin 可以极大地提高开发效率,特别是在开发后台管理系统时。只需将RailsAdmin 引擎添加到...
讨论如何优雅地处理所有404错误页面,为用户提供更好的错误提示信息。 ##### Part II—Database Recipes 这部分则专注于数据库相关的优化策略和技术实现。 **8. Add ForeignKey Constraints** 介绍如何在数据库...
6. **国际化(I18n)**:Devise支持多语言,所有的错误消息和提示都可以通过配置文件进行翻译。 7. **友好的URL**:Devise产生的URLs都是用户友好的,比如 `/users/sign_in` 和 `/users/password/new`,这对于用户...
Rails的强类型和自动验证功能有助于确保数据的完整性和安全性。 在开发过程中,我们还需要关注权限控制和错误处理。例如,使用Devise gem进行用户认证,实现登录、注册、密码重置等功能;通过CanCanCan gem来实现...
- **时间戳自动转换**:当用户提交表单时,Rails会自动将用户输入的时间戳转换为其所在时区的时间,从而避免了时区转换错误。 ##### 修改追踪(Dirty Tracking) 在Rails 2.1中,模型类现在内置了修改追踪功能。这...
按照提示逐步操作即可完成Rails环境的安装。 **注意事项**: - 安装目录路径中不能包含空格。例如,不建议将Rails安装到`D:\Program Files\rails dir\`这样的路径下。这是因为命令行工具在处理包含空格的路径时可能...
提供清晰的错误提示,帮助用户解决问题。 10. **日志记录**:在`log`目录下的日志文件可以提供关于文件上传操作的详细信息,这对于排查问题非常有用。确保日志配置得当,以便在出现问题时能快速定位。 升级Rails...
在Rails应用中集成飞信API,可以实现程序自动发送短信的功能,例如用于验证用户的手机号码或者发送通知。 首先,我们需要理解Ruby on Rails的gem机制。Rails允许开发者通过gemfile来管理依赖,使用`bundle install`...
Rails提供了`flash`对象,可以在不同页面之间传递短暂消息,用于提示用户错误信息。 10. **测试(Test)** 为了确保代码的正确性,项目通常会包含测试文件。Rails支持多种测试框架,如RSpec和Test::Unit,用于编写...
除了这些基础验证之外,Rails还提供了其他验证方法,如`validates_inclusion_of`(验证属性是否在指定的范围内),`validates_exclusion_of`(验证属性是否不在指定范围内),`validates_numericality_of`(验证属性...
10. **错误处理与调试**:框架可能会提供友好的错误提示和调试工具,帮助开发者快速定位和解决问题。 为了充分利用rapid-framework,开发者需要熟悉Java编程,理解MVC模式,以及掌握基本的Web开发概念。同时,利用...
此外,`validates_timeliness` 还提供了错误消息的自定义功能,允许开发者根据需要定制错误提示信息,以更好地向用户反馈问题。 标签中提到的 "rails activerecord validation activemodel" 指出这个插件与Rails的...
常见的后端验证库有Express.js中的Validator、Ruby on Rails的Validations等。 7. **JSON Schema验证**:JSON Schema是一种JSON格式的规范,用于定义JSON数据结构和验证规则。它可以用于前后端的统一数据验证,确保...
【标题】"connect_four_rails" 是一个基于 Ruby on Rails 框架开发的 Connect 四游戏项目。Connect 四游戏是一种策略性棋盘游戏,玩家轮流在垂直、水平或对角线上放置颜色不同的圆盘,目标是形成一条由同色圆盘组成...
在这个登录注册模版中,HTML将用于创建表单元素,如输入框(供用户输入用户名和密码)、按钮(提交或重置表单)以及可能的错误提示信息等。HTML5引入了更多的表单控件和属性,使得创建交互式表单变得更加容易和灵活...
在"jgForca"中,这包括显示已知字母、挂人的图像(代表猜测失败次数)、输入框供用户输入猜测的字母,以及反馈信息(如正确或错误的字母提示)。 3. **控制器(Controller)**:控制器处理用户的请求,调用模型进行...
当模型验证失败时,Rails会自动存储错误信息,并可以通过`object.errors`访问。在视图中,我们可以循环遍历错误并显示给用户: ```erb <h2><%= pluralize(@ship.errors.count, "error") %> prohibited this ...
5. **I18n(国际化)**:Devise支持多种语言,你可以自定义翻译文件来更改默认的错误消息和提示。 6. **安全性设置**:可以调整Devise的安全参数,如会话过期时间、密码复杂度要求等,以提高应用的安全性。 7. **...