Trinity76
Trinity76

Reputation: 665

collection_select: TypeError: ["foo","bar","baz"] is not a symbol nor a string

I have an Imagecapturing table with column city. I want to implement a search form select dropdown list of cities.

In my view, I have a form that should display a dropdown list with cities:

<%= form_tag imagecapturings_path, method: :get do %>
   <%= collection_select(nil, :imagecapturing_id, Imagecapturing.all, :ort, Imagecapturing.cities, prompt: false) %>
   <%= submit_tag("Search", :name=>"submit") %>
<% end %>

In model/imagecapturing.rb:

  def self.cities
    Imagecapturing.distinct.pluck(:city).sort!
  end

In my browser, I get the error message: TypeError in Imagecapturings#index ["foo","bar","baz"] is not a symbol nor a string.

How can I fix the collection_select method call?

Upvotes: 0

Views: 1366

Answers (2)

SRack
SRack

Reputation: 12203

As you're passing nil as the first arg to collection_select, it looks to me as if you should be using a select_tag. This would need to be updated as follows:

<%= form_tag imagecapturings_path, method: :get do %>
   <%= select_tag :imagecapturing_id, options_from_collection_for_select(
     Imagecapturing.all, :ort, :city_name, prompt: false # plus any other desired options
   ) %>
   <%= submit_tag("Search", :name=>"submit") %>
<% end %>

As far as I can tell, collection_select is designed for use with a form object, while select_tag operates without one, as in your use case.

options_from_collection_for_select then takes the options in a similar manner to as you have specified - although, as Ajith has pointed out, the arguments should be a collection, followed by two methods that work on this collection.

The first :ort is the select option's value (more typically an id), the second :city_name, its display name. As in their answer, you'll need to ensure there's a method city_name available for imaginecapturing instances.

The method then returns a string of option tags, that would appear like the following:

'<option value="#{ort}">#{city_name}</option>....and so on'

This last part is where the error lies, and reworking your code to look like the above should resolve your issue.

Upvotes: 1

Ajith
Ajith

Reputation: 345

<%= collection_select(nil, :imagecapturing_id, Imagecapturing.all, :ort, Imagecapturing.cities, prompt: false) %>

in the above line Imagecapturing.cities returns an array. it expects a string or symbol. in simple word it is expecting the text value that need to be displayed for each option.

see this code

<%= form_tag charges_path, method: :get do %>
   <%= collection_select(nil, :id, ImageCapturing.all, :id, :city_name, prompt: false) %>
   <%= submit_tag("Search", :name=>"submit") %>
<% end %>

and my model is

class ImageCapturing < ApplicationRecord

    def city_name
        self.city
    end
end

Modify the id's accordingly.

Thanks, Ajith

Upvotes: 1

Related Questions