2011-08-11 1 views
2

는 다음과 같은 형식을 감안할 때 :레일 3 : 데이터베이스 테이블의 행에서 <select> 태그의 옵션을 만드는 방법은 무엇입니까?

<%= form_for(@ciudad) do |f| %> 
    <% if @ciudad.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@ciudad.errors.count, "error") %> prohibited this ciudad from being saved:</h2> 

     <ul> 
     <% @ciudad.errors.full_messages.each do |msg| %> 
      <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :nombre %><br /> 
    <%= f.text_field :nombre %> 
    </div> 

    <div class="field"> 
    <%= f.label :departamento_id %><br /> 
    <%= f.select :departamento_id , :prompt => "Seleccione el municipio" %> 
    </div> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

어떻게 데이터베이스에서 deparamento_id 선택 태그의 옵션을 채우는 것?

답변

7

가장 간단한 방법은 f.select 대신 f.collection_select을 사용하는 것입니다. 가정 당신은 nombre라는 필드 Departamento라는 테이블/모델을 가지고 :

<%= f.collection_select :departamento_id, Departamento.all, :id, :nombre, :prompt => "Seleccione el municipio" %> 

현재 공식 레일 가이드에 대한 자세한 내용을보실 수 있습니다 : http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

: http://guides.rubyonrails.org/form_helpers.html#option-tags-from-a-collection-of-arbitrary-objects

을 그리고 API 설명서

+2

그건 완전히 rad입니다. – Nic

관련 문제