为什么fields_for没有迭代传递的ActiveRecord :: Relation?

时间:2015-08-06 05:11:46

标签: ruby-on-rails activerecord devise form-helpers fields-for

我试图设置表单的一部分,用户可以选择零个或多个医生,但需要提供每个医生的代币以证明他们与医生交谈。无论如何,我有关于模型的关系,并且可以设置&得到医生和病人的名单。但fields_for似乎并不了解这一点。在某些地方我可能错过了一些魔法,如果有人能指出它是伟大的。

在控制器中:

def edit
  @doctors = User.doctor
  super
end

在模型中:

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

在视图中:

<%= 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 %>

我目前收到错误:undefined method 'id' for #<User::ActiveRecord_Relation:0x007faa9392c9b8>因为整个关系正在fields_for中使用,而不是一次只使用一个实例。

我只是想实现这个:

  

或者要使用的集合:

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

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

2 个答案:

答案 0 :(得分:3)

如果您希望从words获得迭代,则模型中需要accepts_nested_attributes_for :doctors

答案 1 :(得分:0)

<%= f.fields_for :doctors, @doctors do |d| %>替换为<%= f.fields_for :doctor do |d| %>