开发者

Assosiation help in ruby on rails

I have fully linked everything together so a contact belongs_to :company and a company has_many :contacts everything works. The only question i have is in the contacts#new form you have to enter a companies ID is it possible to input the name of the company somehow and for it too translate to an ID in the back end? at the moment my form looks like this. You may notice company_id at the bottom of the form this is the field which i want to change. So that it is more user friendly instead of inserting an ID you insert a name or some kind of list of companies that you select. Please help?

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


You can use collection_select helper or simply select helper to achieve this:

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


Sure can:

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


You can use a drop down list :

Take a look at this thread of how to do it in rails Drop down box in Rails

then as @David Burrows has suggested

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

This should do .

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜