2011-08-18 6 views
0

나는 모든 것을 함께 연결했습니다. belongs_to :companyhas_many :contacts 모든 것이 작동합니다. 내가 가지고있는 유일한 질문은 당신이 회사 ID를 입력해야하는 연락처 # 새로운 양식에있는 것입니다. 어떻게 든 회사 이름을 입력 할 수 있고 백 엔드의 ID로 변환 할 수 있습니까? 지금 내 양식은 이렇게 보입니다. 양식 맨 아래에 company_id가 있습니다.이 필드는 변경하려는 필드입니다. 그래서 ID를 삽입하는 것보다 사용자 친화적 인 방법입니다. 이름을 입력하거나 선택한 회사 목록을 입력하십시오. 도와주세요?루비 레일에 assosiation 도움

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

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

    <div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label :position %><br /> 
    <%= f.text_field :position %> 
    </div> 
    <div class="field"> 
    <%= f.label :email %><br /> 
    <%= f.text_field :email %> 
    </div> 
    <div class="field"> 
    <%= f.label :telephone %><br /> 
    <%= f.text_field :telephone %> 
    </div> 
    <div class="field"> 
    <%= f.label :source %><br /> 
    <%= f.text_field :source %> 
    </div> 
    <div class="field"> 
    <%= f.label :company_id %><br /> 
    <%= f.text_field :company_id %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

답변

4

당신이 달성 collection_select 도우미 또는 단순히 select 도우미를 사용할 수 있습니다

그것을 수행하는 방법이 스레드에서 살펴 보자 :

<%= f.select(:company_id, Company.all.collect {|company| [company.name, company.id]}) %> 
+1

'options_from_collection_for_select'이 :) 또한 –

+1

덕분에 룬 꽤 좋다. – ahmet

0

당신은 드롭 다운 목록을 사용할 수 있습니다 레일 내 Drop down box in Rails

@David Burrows가 제안한대로

<select name="company[name]"> 
    <option value="">Please select</option> 
    <option value="company_id[1]" selected="selected">company[name]</option> 
    <option value="company_id[2]">company[name]</option> 
    <option value="company_id[3]">company[name]</option> 
</select> 

이 작업을 수행해야합니다.

2

물론 할 수 있습니다

<%= select_tag "company", options_from_collection_for_select(Company.all, "id", "name") %>