Reputation: 1017
I am having an issue trying to read the contents of a rails array. (ruby 2.x, rails 4.x)
I have a search form where one of the items is a select multiple. The array is stored in a text field called category. I am getting the array with
<%= f.select :category,
options_for_select(@categories.sort),
{:include_blank => true},
{:multiple => true, :size =>10} %>
If I do a <%= @search.inspect %> I get something like
Search id: 675, document_title: "", summary: "", owner: "[\"\"]", category: "[\"\", \"Apples\", \"Calendar\", \"Forms\"]", file_name: "", created_at: "2015-12-28 13:57:45", updated_at: "2015-12-28 13:57:45", doc_to_email: nil
I see that the category field has an array with the three items I selected.
If I do <%= @search.category %> I see
["", "Apples", "Calendar", "Forms"]
So far, it seems to me that the array is there.
However,
<%= @search.category[0..8] %>
results in
["", "App
<%= @search.category.first %>
[
<%= @search.category.last %>
]
Which was not what I was expecting
<% @search.category.each do |cat_name| %>"
<%= cat_name %>
<% end %>
results in an error of
Showing C:/Users/cmendla/RubymineProjects/technical_library/app/views/searches/show.html.erb where line #85 raised:
undefined method `each' for "[\"\", \"Apples\", \"Calendar\", \"Forms\"]":String Rails.root: C:/Users/cmendla/RubymineProjects/td
Application Trace | Framework Trace | Full Trace app/views/searches/show.html.erb:85:in `_app_views_searches_show_html_erb___938985047_80352240'
What am I doing wrong in trying to read the contents of the array?
Upvotes: 1
Views: 59
Reputation: 18454
Your models' category
is a string, not an array.
To store array in a text field - add
serialize :category, JSON
into model.
Upvotes: 2