Search code examples
ruby-on-railsactiverecorddeviseform-helpersfields-for

Why is fields_for not iterating over the passed ActiveRecord::Relation?


I'm trying to setup a section of the form where a user can select zero or more doctors, but is required to provide a token from each to demonstrate that they spoke to the doctor. Anyway, I have the relationship working on the models, and can set & get lists of doctors and patients. But fields_for doesn't seem to understand that. There's probably some magic somewhere that I've missed, and if anyone can point it out that'd be great.

in the controller:

def edit
  @doctors = User.doctor
  super
end

in the model:

class User < ActiveRecord::Base
  devise :registerable

  has_secure_token
  enum role: [:doctor, :admin, :customer, :distributor]
  enum salutation: [:mr, :mrs, :ms, :miss, :dr]

  has_and_belongs_to_many :doctors, -> { doctor }, {class_name: "User", join_table: :doctors_patients, foreign_key: :patient_id, association_foreign_key: :doctor_id}
  has_and_belongs_to_many :patients, {class_name: "User", join_table: :doctors_patients, foreign_key: :doctor_id, association_foreign_key: :patient_id}
end

in the view:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put,class:"form-horizontal" }) do |f|
  ...
  <%= f.fields_for :doctors, @doctors do |d| %>
    <tr>
      <td><%= d.check_box :id,{checked: resource.doctors.include? d.object.id} %></td>
      <td><%= "#{d.object.salutation.titleize}. #{d.object.last_name}" %></td>
      <td><%= "#{d.object.clinic}" %></td>
      <td><%= d.text_field :token %></td>
      <td><%= link_to 'More','#',class:"btn btn-primary",data:{toggle:"modal",target:"#doctor#{d.object.id}Modal"} %></td>
    </tr>
  <% end %>
<% end %>

I'm currently getting an error: undefined method 'id' for #<User::ActiveRecord_Relation:0x007faa9392c9b8> because the entire relation is being used in fields_for not one instance at a time.

I'm just trying to implement this:

Or a collection to be used:

<%= form_for @person do |person_form| %>
  ...
  <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
    Name: <%= project_fields.text_field :name %>
  <% end %>
  ...
<% end %>

from: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for


Solution

  • Turns out you need accepts_nested_attributes_for :doctors in your model if you want to get the iteration from fields_for.