Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ruby on rails - 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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...