Muhammad Yaseen Muhammad Yaseen - 4 months ago 8
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' %>


index.html.erb

<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">
<thead>
<tr class="tr-head">
<td>Date</td>
<td>Description</td>
<td>Amount</td>
<td>Discount</td>
<td>Paid</td>
<td>Balance</td>
</tr>
</thead>

<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 %>
<p>
<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>
</p>
<% end %><br>
</div>


<tbody>
<%= render(@xvaziris) || 'No records' %>
</tbody>
</table>
</div>
</div>
</div>


index.js.erb

<% @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

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
           value
         else
           1
         end
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
Comments