为什么 content_tag 帮助程序打印“flash”?浏览器中的内容?
为了进一步解释,我的 Rails 应用程序布局中有以下代码:
<!-- Stuff omitted -->
<% unless flash.empty? %>
<%= flash.each do |name, msg| %>
<%= content_tag :div, msg, :id => "flash_#{name}" %>
<% end %>
<% end %>
<%= yield %>
对于控制器:
#stuff omitted
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render :new
end
end
好的,所以,如果我碰巧身份验证失败,这就是我在浏览器中看到的内容:
你们能告诉我为什么哈希值({:alert => "无效的电子邮件或密码"}) 出现在消息下方吗?我真的不知道出了什么问题,
(顺便说一句,这取自 Rails Casts #250)
To explain further, I have the following code in my Rails app Layout:
<!-- Stuff omitted -->
<% unless flash.empty? %>
<%= flash.each do |name, msg| %>
<%= content_tag :div, msg, :id => "flash_#{name}" %>
<% end %>
<% end %>
<%= yield %>
And for the controller:
#stuff omitted
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render :new
end
end
Ok, so, If I happen to fail the authentication, this is what I'm seeing in the browser:
Can you guys tell me why is the hash({:alert => "Invalid email or password"}) appearing under the message? I'm really clueless about what is wrong,
(BTW, This is taken from Rails Casts #250)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需从循环开头删除等号即可:
因为它告诉 ERB 打印整个
flash
变量。Just remove the equal sign from the start of the loop:
Because it tells ERB to print entire
flash
variable.看起来消息最终变成了散列。尝试像这样设置 Flash 消息:
It looks like message ends up being a hash. Try setting the flash message like this:
您可以尝试以下操作:
在
application.html.erb
中您可以编写:在控制器中你可以写:
flash[:danger] = "无效的电子邮件或密码"
You can try the following:
in
application.html.erb
you can write:in controller you can write:
flash[:danger] = "Invalid email or password"