Search code examples
ruby-on-railsstringflags

Why scan method for strings prints out directly in rails and ingnore the rest of code


I have a field (string) in DB that stores a list of values gotten from checkbox if they are checked:

Example:

checkbox1 [X] //Value 1
checkbox2 [ ] //Value 2
checkbox3 [X] //Value 3
checkbox4 [X] //Value 4
checkbox5 [ ] //Value 5

It stores in database the string "--- -'1' -'3' -'4'" (w/o the double quotes) I don't know why because in my form I have:

<%  SoProfile::LANGUAGES.each do |key, value| %>
  <div class="fluid">
    <%= f.label :languages,class: "checkbox" do %>
      <%= key %> <%= f.check_box :languages, {:multiple => true}, value, nil %>
    <% end %>
  </div>
<% end %>

in the model (I don't want to use a DB table for this):

LANGUAGES = { Espanol: 1, Ingles: 2, Portugues: 3, Italiano: 4, Mandarin: 5 }

anyways, it stores that string "--- -'1' -'3' -'4'" for the example above, I want to show a country flag according to the language instead of putting the language name.

I've created a helper method for this:

def insert_languages(string)
  string.scan(/\d/).each do |i|
    case i
      when i == "1"
        content_tag(:div,"",class: 'flag flag-co')
      end
  end
end

that is called in my view:

<tr>
  <td>Idiomas <br /> 
    <%= insert_languages(@so_profile.languages) %>                                                                                   
  </td>
</tr>

But the helper method won't pass from .scan and will print out the hash ["1" "3" "4"] directly, it is, it never reaches the case code, like if there were a return in the string.scan(.. line of code.

How can I prevent rails from returning the hash and instead print the flag?


Solution

  • Try changing your method to following:

    def insert_languages(string)
      result = ""
      string.scan(/\d/).each do |i|
        case i
          when "1"
            result += content_tag(:div,"",class: 'flag flag-co')
          end
      end
      result
    end
    

    You're getting hash since ruby returns values from .each block. Ruby returns last value from function implicitly. About your storing method - I suggest you reconsider your storage method. In mongoid, for example, you can use arrays. For active record something like that could solve your problem.