Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accept nested attributes for has_many relationship

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:

like image 812
Chris Muench Avatar asked Feb 24 '23 21:02

Chris Muench


2 Answers

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

like image 182
Chris Muench Avatar answered Mar 06 '23 23:03

Chris Muench


In Rails 3 (not sure about previous versions) you don't even need to use accepts_nested_attributes_for to accomplish this. You can simply remove all the view code you listed and replace it with the following:

<%= patient_form.select(:client_ids, @clients.collect {|c| [ c.name, c.id ] }, {}, {:multiple => true})%>

Rails will do its magic (because of you named the select "client_ids") and it will just work.

like image 21
dmin Avatar answered Mar 06 '23 23:03

dmin