简体   繁体   中英

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. 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:

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

If you're using rails (& therefore activesupport) the .blank? (suggested by others) works for all those cases

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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