Jan
Jan

Reputation: 259

Connecting two models belongs_to/has_many and selecting via dropdown in form

I am rails beginner and I am facing a basic problem. I have found a couple of solutions but none of them fully describe my problem. I have two models: Contact and Group

Group has_many :contacts
Contact belongs_to :group

(Through devise there is a third user model)

When creating a new contact I wish that the user will be able to select the group that this contact belongs to via a select option (like a dropdown field).

I have added a :group_id index to he contacts table:

class AddGroupIdToContacts < ActiveRecord::Migration
  def change
    add_column :contacts, :group_id, :integer
  end
end

In the view/contacts/_form I have used the collection_select option to output a dropdown field showing the available groups:

<%= 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 |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  ...

  <div class="field">
    <%= f.label :group_id %><br>
    <%= f.collection_select(:group_id, Group.all, :id, :name) %>
  </div>

  ...

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

I can input a new contact successfully but when checking in the console I have an empty group_id: nil field.

What is the correct way to input the id of the selected Group into the group_id field and how can I display this entry (preferably by using the name of the groups id) in the show.html.erb?

I know this is a basic questions but I stuck and pretty new to rails. Thanks for your help!

Upvotes: 2

Views: 1498

Answers (2)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

<%= f.select :group_id, options_from_collection_for_select(Group.all, 'id', 'name') %>

This will help you.

Upvotes: 6

Anuja
Anuja

Reputation: 654

I tried above code and its working fine. I can save contact with group_id without any change in your code. Please check again. Are you getting group_id in params in controller?

Upvotes: 0

Related Questions