如何防止在index.html.erb上显示hash []

时间:2016-09-15 19:17:48

标签: ruby-on-rails

尝试此代码:

def index
    if @todos = Todo.all.nil?
        redirect_to todos_path, :notice =>  "No Tasks Yet"
    else
        @todos = Todo.all
    end
end

a)页面空白时不显示通知 b)空白时在[]页面上显示index.html.erb标记

如果空白时如何阻止[] index.html.erb出现?以及如何显示通知?

如果需要进一步的代码,请告诉我。

谢谢

修改

在index.html.erb页面上包含哈希标记的屏幕截图

enter image description here

编辑2

到目前为止这是index.html.erb页:

<h1>Todo List</h1>

<%= link_to "Create New Todo", new_todo_path %>

<%= @todos.each do |t| %>
    <li><%= t.name %></li>
<% end %>

编辑3

这是当前的application.html.erb代码

  <body>

    <% flash.each do |key, value| %> 
    <div class="alert alert-<%= key %>">
        <%= value %>
    </div> 
    <% end %>

    <%= yield %>

  </body>

1 个答案:

答案 0 :(得分:1)

您正在检查nil而不是empty?。您应该使用blank?代替。 您还使用单个=来检查==的相等性。

@todos = Todo.all.nil?更改为@todos == Todo.all.blank?

  

如果对象为false,空或空白字符串,则该对象为空。对于   例如,假,&#39;&#39;,&#39; &#39;,nil,[]和{}都是空白的。

尝试以下方法:

def index
  if @todos == Todo.all.blank?
    flash[:notice] = 'No Tasks Yet'
    redirect_to todos_path
  else
    @todos = Todo.all
  end
end