Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checking if Element is Present in an Array in Rails View

I’m encountering an issue while trying to check if a string is present in an array within my Rails application. The include? method seems to be giving unexpected results.

I have an array named @categories which holds a list of strings like ["poverty", "hunger"]. I’m trying to use this array to pre-select checkboxes in a form based on whether the values where selected last time.

In this code, I print the values @categories, @categories&.include?(un_kind[1]), and un_kind[1], which give me the following respective values:["poverty", "hunger"] false poverty

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<%= @categories %>
<% Array(t("#{cat_l}.enums.un_kind").invert).each do |un_kind| %>
  <%= @categories&.include?(un_kind[1]) %>
  <%= un_kind[1] %>
  <div class="form-check">
    <%= check_box_tag "un_kind[]", un_kind[1], @categories&.include?(un_kind[1]), class: 'form-check-input' %>
    <%= label_tag "un_kind_#{un_kind[1]}", un_kind[0], class: 'form-check-label' %>
  </div>
<% end %>

>Solution :

The problem here is a string vs symbol issue. You’re getting your un_kind[1] from your i18n locale lookup, which means it will be :poverty NOT "poverty". Therefore:

> ["poverty", "hunger"].include? :poverty
false

…as opposed to:

> ["poverty", "hunger"].include? "poverty"
true

The confusing part here is that when you print a symbol it’s automatically converted to its string form. This is why generally for debugging it’s better to use inspect on the objects that you’re printing, that will usually give you better visibility as to what’s going on.

I’m sure you’re way ahead of me, the simple fix is to .to_s your un_kind[1] object: @categories&.include?(un_kind[1].to_s)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading