Accept nested attributes for has_many relationships

Below are two of my 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 box with several choices where the patient can be assigned to clients. Is there any way to do this, so I don't need to have any logic in the controller except

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

I 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 he only saves the first customer. If I remove several parts, it will work, but I can only choose one client!

Html value to select:

+4
source share
3 answers

I ended up doing the following:

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

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

+4
source

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 view code that you specified 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 you called select "client_ids") and it will work.

+4
source

Instead

 :client_id 

in collection_select, try

 "client_id[]" 

The second form indicates that you are accepting an array of identifiers for the attribute, not one.

Here's a good resource on using selected helpers in forms: http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails

0
source

Source: https://habr.com/ru/post/1342336/


All Articles