Die*_*ano 5 ruby flash validation ruby-on-rails twitter-bootstrap
我是Ruby on Rails的新手,也是这个网站的新用户.我试图让我的控制器上的错误来自我在模型上设置的验证,因此我可以根据是否发生错误来更改闪存消息.
我有这样的验证:
class User < ActiveRecord::Base
attr_accessible :login, :password
validates_presence_of :login , :message => 'Login can't be empty'
validates_presence_of :password ,:message => 'Password can't be empty'
Run Code Online (Sandbox Code Playgroud)
我的控制器中有这个代码:
def create
login = params[:username].downcase
password = params[:password]
tuser=User.new(login: login, password: password).save
if(tuser.errors.any?)
flash[:title]='¡Error!'
flash[:notice]='Please verify your data'
else
flash[:title]='¡Success!'
flash[:notice]='Your account was created'
end
Run Code Online (Sandbox Code Playgroud)
我在我的html上使用这个flash对象来渲染一个bootstrap模式:
<% if flash[:notice] %>
<div class="modal hide fade" id="modal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h3><%= flash[:title] %></h3>
</div>
<div class="modal-body">
<%= flash[:notice] %>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
控制器中出现问题,我收到此错误:
NoMethodError in UserController#create
undefined method `errors' for false:FalseClass
Run Code Online (Sandbox Code Playgroud)
我想将我的flash [notice]错误消息更改为验证引发的错误消息,但我不能这样做.我已经按照一些教程,但他们使用.html文件上的@tuser全局变量来获取验证错误消息,我需要在控制器上处理它们.谁能帮我?
谢谢
当您调用 save 时,它会进行验证,然后返回True保存是否成功,或者False如果保存失败,则您将 tuser 设置为True或False当您调用 save 时。如果 Save 为 false,则会生成错误并可访问,因此无需检查错误。尝试这个:
def create\n login = params[:username].downcase\n password = params[:password]\n @tuser=User.new(login: login, password: password)\n #you could also use @tuser = User.new(params[:user]) but you will have to rename :username to :login\n if tuser.save\n flash[:title]='\xc2\xa1Success!'\n flash[:notice]='Your account was created'\n #redirect_to user_path(@tuser)\n else\n flash[:title]='\xc2\xa1Error!'\n flash[:notice]='Please verify your data'\n #render 'new'\n end\nend\nRun Code Online (Sandbox Code Playgroud)\n\n您可能还应该向上面注释的代码添加重定向或渲染,因为我不知道您从哪里调用它。
\n\n编辑\n此外,将小写字母添加到模型中将与 Rails 更加一致,例如
\n\nbefore_save {|user| user.login = login.downcase}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
6858 次 |
| 最近记录: |