Rails:当数据库中没有元素时显示消息的优雅方式 [英] Rails: An elegant way to display a message when there are no elements in database
问题描述
我意识到我正在编写很多与此类似的代码:
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 %>
推荐答案
如果您使用 :collection
参数来渲染,例如render :partial =>'消息', :collection =>@messages
那么如果集合为空,则对渲染的调用将返回 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' %>
如果您以前没有遇到过,render :collection
为每个元素使用相同的部分渲染一个集合,使 @messages
的每个元素都可以通过局部变量 message
建立完整的响应.您还可以使用 :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屋!