Closed happypeter closed 10 years ago
判断有无该项错误:
irb(main):008:0> u.errors[:name].any?
=> true
Furthermore, if you use the Rails form helpers to generate your forms, when a validation error occurs on a field, it will generate an extra
around the entry.<div class="field_with_errors"> <input id="post_title" name="post[title]" size="30" type="text" value=""> </div>
http://guides.rubyonrails.org/active_record_validations.html#displaying-validation-errors-in-views
如果要在视频中重复一遍 http://railscasts.com/episodes/250-authentication-from-scratch-revised 中的内容就太多了
我主要想讲的内容:
以开始想用投机取巧的方法,绕过 i18n,所以用了很多:
validates_presence_of :name, :message => "不能为空"
validates_uniqueness_of :name, :case_sensitive => false, :message => "已被占用"
validates_presence_of :email, :message => "不能为空"
validates_uniqueness_of :email, :case_sensitive => false, :message => "已被占用"
也就是直接给出中文报错信息作为参数。但是有些错误就不知道怎么传入中文 error 了,例如来自 has_secure_password 给出的相关报错 does not march confirmation
。
所以还是走一下正规流程吧: http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models http://stackoverflow.com/questions/808547/fully-custom-validation-error-message-with-rails
好在只要把 application.rb
中加入
config.i18n.default_locale = 'zh-CN'
报错信息就会显示为:translation missing: zh-CN.activerecord.errors.models.user.attributes.password.confirmation
rails new baby -d mysql
application.rb
config.generators do |g|
g.assets false
g.helper false
g.test_framework false
end
rake db:create;rake db:migrate
rails g model user name:string email:string password_digest:string token:string
rake db:migrate
rails g controller users welcome signup login
route.rb
Signup::Application.routes.draw do
root to: "users#welcome"
get "login" => "users#login", :as => "login"
get "signup" => "users#signup", :as => "signup"
post "create_login_session" => "users#create_login_session"
delete "logout" => "users#logout", :as => "logout"
resources :users, only: [:create]
end
rm public/index.html.erb
rails s