Search code examples
ruby-on-railsrubyruby-on-rails-5

Am unable to use the foreach loop in the template in Ruby on Rails


What I want to do is use the

erb select and the foreach loop

to create a select menu(drop down menu) and these are what have done Step 1: create the State model and migrate the created ruby file with

rails db:migrate

Step2: Include @state in the StaticController like

def index
  @states = State.new
end

And in the view which is the last step did this

<%= f.label :state %>
 <% @states.each do |state| %>
 <%= f.select :state, (value:state.states) %>
<% end %>

And this is the error I got

undefined method `each' for #State id: nil, states: nil, created_at: nil, updated_at: nil

Meanwhile in the PGAdmin(Postgre Admin), have inserted some names and I can view them in PGAdmin


Solution

  • You did two mistakes:

    1. I don't think you want to initialize a new object of State, probably you want to get all states, in this case, you should use State.all;

    2. The way you did to set the options for the select isn't correct, take a look at the documentation (one way to pass the options for the select helper is f.select(:state_id, @states.collect { |state| [ state.name, state.id ] })).