Ruby-on-rails – accept nested attributes for has_many relationship

ruby-on-rails

Below are my two model classes

class Patient < ActiveRecord::Base
  belongs_to :user, :dependent => :destroy
  has_many :enrollments, :dependent => :destroy
  has_many :clients, :through => :enrollments

  accepts_nested_attributes_for :user
  accepts_nested_attributes_for :enrollments
  attr_accessible :user_attributes,:enrollments_attributes, :insurance
end

class Enrollment < ActiveRecord::Base
  belongs_to :client
  belongs_to :patient
  attr_accessible :client_id, :patient_id, :patient_id, :active 
end

In my patient form I would like to have a multi select box where a patient can be assigned to clients. Is there a way this can be done so I don't have to have any logic in the
controller except for

@patient = Patient.new(params)
@patient.save

I have tried this:

<%= patient_form.fields_for :enrollments do |enrollments_fields| %>
<tr>
    <td class="label">
        <%= enrollments_fields.label :client_id %>:                     
    </td>
    <td class="input">
        <%= enrollments_fields.collection_select(:client_id, @clients, :id, :name, {}, :multiple => true) %>
    </td>                   
</tr>
<% end %>

But it only saves the first client. If I remove the multiple part, it functions but I can only select 1 client!

The html value of the select is:

Best Answer

I ended up doing the following:

<%= check_box_tag "patient[client_ids][]", client.id, @patient.clients.include?(client) %>

I am not sure if this is the best way...any comments (I had to update my model to include attr_accessible :client_ids

Related Topic