Dave
Dave

Reputation: 1175

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!

Upvotes: 8

Views: 9991

Answers (2)

Tan Nguyen
Tan Nguyen

Reputation: 3376

As aNoble said, it's right! If you want to order by name, just use the following:

<%= f.collection_select :area_id, Area.order(:name), 
    :id, :name %>

Upvotes: 0

aNoble
aNoble

Reputation: 7072

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) %>

Upvotes: 29

Related Questions