【问题标题】:simple_form rails 4, set automatic associationsimple_form rails 4、设置自动关联
【发布时间】:2015-11-12 21:35:47
【问题描述】:

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

<%= f.association :patient %>

我以这种方式将患者的 id 参数传递给操作“新”:

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

在我看来:

  1. 我怎样才能让 f.association 字段自动获取对应的患者 ID?

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

  3. 如果我想隐藏这个字段,如果我放就可以了

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

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

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 associations simple-form


    【解决方案1】:

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

    这是一个Patient 对象

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

    --

    f.association field自动带走通讯员patient_id

    This 可能会有所帮助:

    看起来组织模型没有以下任何字段:[ :to_label, :name, :title, :to_s ] 所以SimpleForm 无法检测到默认值 用于收集的标签和值方法。我认为你应该通过它 手动。

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

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

    -

    我如何确定 patient_id 是当前患者?

    如果您必须对此进行验证,则表明您的代码结构存在不一致。如果您需要将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
    

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

    【讨论】:

    • 感谢您花时间向我解释。我意识到我必须更多的研究和学习来开发这个应用程序,现在我认为我使用脚手架构建这个应用程序是错误的,我不知道有什么书可以帮助我深入理解如何管理孤立的用户(实例),并在我的应用程序中管理控制器中的关系,你知道有什么书可以帮助我吗?无论如何感谢您的帮助
    【解决方案2】:

    您希望使用 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_。

    【讨论】:

    • 当我今天在不那么累的时候重读你的问题时:O - 我意识到我实际上并没有回答你的问题。不过,我将保留此回复,希望其他人发现它有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多