I want to be able to select a city from an existing array of cities.
I have stored the cities in an array in the ControllerName controller as a global variable
$cities = ["city1"...."city20"]
and I want to be able to access them via : <%= p.select(:city, $cities{ |c| [c.name, c.id]}) %>
but then I receive the error message undefined method name for 'city1'
.
How can I select from that existing array? Should I make some controller for cities?
Update #1
I came to make this code
$cities=['city1',...'city20']
@city = Array.new
i = $cities.size
i.times do |x|
@city[x] = City.new
@city << $cities[x]
end
and instead of undefined method
name' for "City1":StringI got
undefined method name' for "City20":String
PS : the table of cities has a column named 'name', so the problem isn't particularly there
Update #2 : Issue Solved
After reading a bit in this Rails Documentation I was able to make a little improvement on my code and I actually could solve the issue.
In my form , I have edited the code to that :
<%= p.select(:city, options_for_select( @cities_array ) )%>
And in my ControllerName Controller , I have put this :
$cities.length.times do |x|
@city = City.new({:name => $cities[x]})
@city.save
end
@cities_array = City.all.map { |city| [city.name, city.id] }
And that was all to it.
If you have any alternative solution , be it simpler or more complex, please share it as an answer.
You have multiple options to insert data into your database.
The first one. Add this on a migration:
rails generate migration add_cities_rows
inside your migration you can add something like:
cities = ['city1', 'city2', 'city3']
cities.each {|city| City.create(name: city)}
then you can run: rake db:migrate
You can add the same logic in db/seeds.rb
file so if you want to regenerate your database running rake db:setup
it will do the magic.
In your view
(where you are using the select helper you can use the following sintaxis to fill the select:
<%= p.select :city, City.pluck(:name, :id) %>
So in your controller yo don't needto add any logic