我正在尝试设置表单的一部分,用户可以在其中选择零个或多个医生,但需要提供来自每个医生的令牌来证明他们与医生交谈过。总之,我在模型上建立了关系,可以设置&获取医生和病人的名单。但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
如果您想从fields_for
获得迭代,那么您需要在模型中使用accepts_nested_attributes_for :doctors
。
用<%= f.fields_for :doctor do |d| %>
代替<%= f.fields_for :doctors, @doctors do |d| %>
行。