Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Rails dropdown for related database

I have 2 models, venues and areas (areas consists of id and name fields). They are related as: one area has many venues and each venue belongs to an area.

To assign a venue to an area I am currently entering the area_id number into a text field in the create new venue page. I can then display which area the venue belongs to with:

<%= venue.area.name %>

Instead of having to enter the ID number of the area in the form I would like to have a dropdown listing the area names for all the area records and for the selected one to be associated with that venue on save.

The new venue form:

<% form_for @venue do |f| %>
  <p>name: <br>
  <%= f.text_field :name %></p>

  <p>address line 1: <br>
  <%= f.text_field :addressline1 %></p>

  <p>address line 2: <br>
  <%= f.text_field :addressline2 %></p>

  <p>address line 3: <br>
  <%= f.text_field :addressline3 %></p>

  <p>area_id: <br>
  <%= f.text_field :area_id %></p>

  <%= submit_tag %>
<% end %>

I have tried:

  <p>area_id: <br>
  <%= collection_select(:area, :name, @areas, :id, :name) %>

But get:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.map

Any help is much appreciated!

like image 686
Dave Avatar asked Jan 19 '11 19:01

Dave


1 Answers

It looks like @areas isn't defined and maybe a couple other issues as well. Try this:

<%= f.collection_select(:area_id, Area.all, :id, :name) %>
like image 123
aNoble Avatar answered Oct 21 '22 18:10

aNoble