Rails:在数据库中没有元素时显示消息的优雅方式 [英] Rails: An elegant way to display a message when there are no elements in database

查看:87
本文介绍了Rails:在数据库中没有元素时显示消息的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到我写了很多与此类似的代码:

I realized that I'm writing a lot of code similar to this one:

<% unless @messages.blank? %>
  <% @messages.each do |message|  %>
    <%# code or partial to display the message %>
  <% end %>
<% else %>
  You have no messages.
<% end %>

Ruby和/或Rails中是否有任何构造可以让我先跳过
条件?所以当迭代器/循环甚至不会进入一次时会执行它?对于
示例:

Is there any construct in Ruby and/or Rails that would let me skip that first condition? So that would be executed when iterator/loop won't enter even once? For example:

<% @messages.each do |message| %>
  <%# code or partial to display the message %>
<% and_if_it_was_blank %>
  You have no messages.
<% end %>


推荐答案

如果您使用:集合要渲染的参数,例如 render:partial => 'message',:collection => @messages 然后,如果集合为空,则对render的调用将返回 nil 。然后可以将其合并到||中表达式例如

If you use the :collection parameter to render e.g. render :partial => 'message', :collection => @messages then the call to render will return nil if the collection is empty. This can then be incorporated into an || expression e.g.

<%= render(:partial => 'message', :collection => @messages) || 'You have no messages' %>

如果你之前没遇到它,渲染:collection 使用相同的部分为每个元素呈现一个集合,通过局部变量消息使 @messages 的每个元素可用因为它建立了完整的响应。您还可以使用指定要在每个元素之间呈现的分隔符:spacer_template => message_divider

In case you haven't come across it before, render :collection renders a collection using the same partial for each element, making each element of @messages available through the local variable message as it builds up the complete response. You can also specify a divider to be rendered in between each element using :spacer_template => "message_divider"

这篇关于Rails:在数据库中没有元素时显示消息的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆