简体   繁体   English

rails if语句,如果未找到任何记录

[英]rails if statement, if no records found

I'm trying to create an if statement so that if there are no records found, a default message is displayed. 我试图创建一个if语句,以便如果找不到记录,则显示默认消息。 I currently have this: 我目前有这个:

- if @n == nil || @n ==""
  welcome
- else
  - @n.each do |n|      
    = n.name
    = raw " - "
    = n.company

but it ignores the first line and just shows the record when necessary. 但它忽略第一行,仅在必要时显示记录。

    - if @n.blank?
      welcome
    - else
      - @n.each do |n|      
        = n.name
        = raw " - "
        = n.company

Try to query the instance variable for blank? 尝试查询实例变量的空白? :

- if @n.blank?

If in a method 如果采用某种方法

if @object.blank?
 #whatever you want to happen
else
 #whatever you want to happen

If in a block 如果在街区

<% if @object.blank? %><%= #foo %>
<% else %>
<%= #bar %>
<% end %>

I think @n is supposed to be an array of objects, not a string, so you should rather check if it's empty: 我认为@n应该是对象数组,而不是字符串,因此您应该检查它是否为空:

if @n == nil || @n == []

If you're using rails (& therefore activesupport) the .blank? 如果您使用的是rails(&因此是activesupport).blank? (suggested by others) works for all those cases (由他人建议)适用于所有这些情况

nil.blank? #=> true
"".blank? #=> true
[].blank? #=> true 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM