webmagnets
webmagnets

Reputation: 2296

How to check if an ActiveRecord table entry is empty

I am not sure if the title of this question uses proper jargon, but hopefully this description will help. If you need more information, please let me know.

I am taking Chinese text from a form and splitting it into a 2d array of sentences and words. I then want to define all the words using dictionary entries in my database. Some of the words aren't in the database, so I want to check for that. What I am trying isn't working.

Here is my current code:

<% @lesson.parsed_content.each_with_index do |sentence, si| %> #iterate 1st dimension
  <% sentence.each_with_index do |word,wi| %> #iterate 2nd dimension
    <% sentence = sentence.to_s %>
    <div class="word blt" id="<%= wi %>">
    <div class="definition blt">
        <% definition = DictionaryEntry.where(:simplified => word) %> #search by simplified chinese
        <% definition.find_each do |w| %>
        <% if w.definition == nil %> # PROBLEM: this never returns true.
            <%= word %>
            <% else %>
        <%= w.definition %>
        <% end %>
        <% end %>
    </div>
    <div class='chinese blt'> <%= word %></div>
    </div>
  <% end %>
<% end %>

How can I change <% if w.definition == nil %> to return true if there is no definition in my database?

Upvotes: 1

Views: 692

Answers (1)

thank_you
thank_you

Reputation: 11107

This is a shot in the dark but first I would switch your code around when you are converting the variable sentence to a string and looping through it. (unless you have a reason for it being that way)

<% sentence = sentence.to_s %>
<% sentence.each_with_index do |word,wi| %> #iterate 2nd dimension

Second, depending on how your data was put inside the database it might be an empty string instead of nil. So I would change the condition from

<% if w.definition == nil %> # PROBLEM: this never returns true.

to

<% if w.definition.blank? %> # Checks to see if definition is blank

Blank will check if its false, empty, or a whitespace string.

Finally, indentation is helpful especially when running loops and conditionals. It's easier on the eyes and helps you understand what's going on.

<% @lesson.parsed_content.each_with_index do |sentence, si| %> 
  <% sentence = sentence.to_s %>
  <% sentence.each_with_index do |word,wi| %> 
    <div class="word blt" id="<%= wi %>">
      <div class="definition blt">
      <% definition = DictionaryEntry.where(:simplified => word) %> 
      <% if definition.empty? %>
        <% word %>
      <% else %>  
        <% definition.find_each do |w| %>
          <%= w.definition %>
        <% end %>
      <% end %>
      </div>
      <div class='chinese blt'> <%= word %></div>
    </div>
  <% end %>
<% end %>

Let me know the results.

Upvotes: 2

Related Questions