Muhammad Yaseen Muhammad Yaseen - 1 year ago 61
Javascript Question

Rails 4.2.0 : Display message when collection is empty

I tried with this in my index.html.erb but it didn't work.

<%= render(@xvaziris) || 'No records' %>


<div class="row">

<div class="col-md-10 col-md-offset-1">

<div class="table-responsive myTable">

<table id = "kola" class="table listing text-center">
<tr class="tr-head">

<a href="#" class="toggle-formed" style="float: right;" ><strong>Search</strong></a>

<div id="sample">

<%= form_tag xvaziris_path, remote: true, method: :get, class: "form-group", role: "search" do %>
<center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", autofocus: true, class: "form-control-search" %>
<%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>
<% end %><br>

<%= render(@xvaziris) || 'No records' %>


<% @balance = 0 %>
$('#kola tbody').empty();
<% @xvaziris.each do |xvaziri| %>
$('#kola tbody').append("<%= j render xvaziri %>");
<% end %>

Do I need to wrap it somewhere in index.js.erb in order to function.

Any suggestions are most welcome.

Thank you in advance.

Answer Source

I think you might want something like this:

<% if @xvaziris.empty? %>
  <em>No records</em>
<% else %>
  <%= render(@xvaziris) %>
<% end %>

Or another, shorter, but less readable way:

<%= @xvaziris.present? ? render(@xvaziris) : "No Records" %>

I personally prefer the first solution

So you're asking why your solution does not work.. It's because render returns a string. (Which in your case is empty)

The || operator is like a short if/else: let's say you have a value which is nil, then you do this:

value = nil
value || 1 # => will return 1

now the if/else way:

value = nil
result = if value
result # => will return 1

Now in your case:

value = render(...) # => "" (empty string)
value || "something else" # => "" (empty string)

this is because an empty string does not return false

to check if a value is true or false you can use double negotiation (!! operator) it's just a way to cast an object to a boolean.

empty_string = ""
!!empty_string # => true

!!nil # => false
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download