simple_form rails 4、设置自动关联

simple_form rails 4, set automatic association

是一个小项目,我尝试将患者模型与咨询联系起来。一位患者 has_many :咨询,在我的表格中我有:

<%= f.association :patient %>

我通过这种方式将患者的id参数传递给动作'new':

<%= link_to new_consultum_path(:id => @patient.id) %>

在我看来:

  1. 如何让 f.association 字段自动接收通讯员 patient_id?

  2. 如何确定patient_id就是当前患者?

  3. 如果我想隐藏这个字段是可以的,如果我把

    代替
  4. 有更好的方法吗?

  5. 为什么在视图中显示我#patient:0x007f4e7c32cbd0?

感谢您的帮助。

您想使用 fields_for 将咨询与患者相关联,这与 form_for 类似,但不构建表单标签。

如果您从患者对象开始,您可以遍历将其绑定到表单字段的咨询关联。

看起来像这样

<%= form_for @patient do |patient_form| %>
    <% patient_form.text_field :any_attribute_on_patient %>
    <% @patient.consultations.each do |consultation| %>
        <%= patient_form.fields_for consultation do |consultation_fields| %>
            <% consultation_fields.text_field :any_attribute_on_consulatation %>
        <% end %>         
    <% end %>
<% end %>

抱歉,代码可能不完全正确。

查看 field_for here

的文档

您还必须设置 accepts_nested_attributes_for 患者咨询。当您设置 accepts_nested_forms_for 时,Rails 将自动更新与患者相关的咨询对象并保存您所做的任何编辑。您绝对想使用 accepts_nested_attributes_for 这种类型的大多数嵌套表单处理。

And why in the view shows me # patient:0x007f4e7c32cbd0

这是一个Patient对象

这意味着你需要调用这个对象的一个​​属性 - EG @patient.name.

--

f.association field take the correspondent patient_id automatically

This 可能有帮助:

It looks like Organization model doesn't have any of these fields: [ :to_label, :name, :title, :to_s ] so SimpleForm can't detect a default label and value methods for collection. I think you should pass it manually.

#app/models/patient.rb
class Patient < ActiveRecord::Base
   def to_label 
      "#{name}"
   end
end

显然,您需要在模型中使用 titlenameto_label 方法,以便 f.association 填充数据。

-

How can I be sure that the patient_id is the current patient?

如果您必须对此进行验证,这表明您的代码结构不一致。如果你需要将patient_id设置为current patient,当然你可以在控制器中设置它:

#app/controllers/consultations_controller.rb
class ConultationsController < ApplicationController
   def create
      @consultation = Constultation.new
      @consultation.patient = current_patient
      @consultation.save
   end
end

如果需要,我可以提供更多上下文。