开发者

Creating a Rails dropdown for related database

I have 2 models, venues and areas (areas consists of id and name开发者_C百科 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!


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜