Ruby on Rails,而不是更新使模型的新入口

时间:2013-06-16 13:27:58

标签: ruby-on-rails ruby ruby-on-rails-3

我制作了一个简单的演示网站,其中包含患者姓名(name:string)的模型和另一个治疗(content:text)的模型。我创建了这个“项目”,以了解有关标记accepts_nested_attribute和fields_for标记的更多信息。 现在我的问题是在患者展示页面上我创建了一个嵌套的治疗方案,就像你在这里看到的那样:

<p id="notice"><%= notice %></p>

<p>
<b>Name:</b>
    <%= @patient.name %>
</p>

<ol>
  <% for treatment in @patient.treatments %>
     <li><%= treatment.content %></li>
   <% end %>
</ol>

<%= form_for(@patient) do |f| %>

<%= f.fields_for :treatments do |builder| %>

<div class="field">
   <%= builder.label :content %><br />
   <%= builder.text_field :content %>
</div>
<% end %>

<div class="actions">
  <%= f.submit %>
</div>
<% end %>

<%= link_to 'Edit', edit_patient_path(@patient) %> |
<%= link_to 'Back', patients_path %>

所以我的问题是在builder.text_field :content更好的调用输入显示最后保存的治疗来自<%= builder.content %>,但我希望他不更新它而不是我想添加新治疗!希望有人理解我!感谢

1 个答案:

答案 0 :(得分:1)

我会创建单独的控制器来仅创建treatment,例如。

# treatments_controller.rb
class TreatmentsController < ApplicationController

  def create
    @patient = Patient.find(params[:patient_id])
    @treatment = @patient.treatments.new(params[:treatment])
    if @treatment.save
      redirect_to @patient
    else
      # handle unsuccessful treatment save
    end
  end
end

# routes.rb:
resources :patients do
  resources :treatments, only: :create
end

# form:
<%= form_for @patient, @treatment do |f| %>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_field :content %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

您还应该在@treatment操作中设置patient#show变量,如下所示:

@treatment = @patient.treatments.new