ahmet
ahmet

Reputation: 5005

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

Upvotes: 0

Views: 86

Answers (3)

Matthew
Matthew

Reputation: 13332

Sure can:

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

Upvotes: 2

Anubis05
Anubis05

Reputation: 1274

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 .

Upvotes: 0

Arun Kumar Arjunan
Arun Kumar Arjunan

Reputation: 6857

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

Upvotes: 4

Related Questions