【问题标题】:UnknownAttributeError in Controller控制器中的 UnknownAttributeError
【发布时间】:2013-07-22 20:45:10
【问题描述】:

在@Sasha 的帮助下,我为患者的治疗创建了一个嵌套表格:

现在我得到这个错误:

UnknownAttributeError in PatientsController#update

unknown attribute: treatment

我的患者更新控制器实际上如下所示:

def update
  @patient = Patient.find(params[:id])

  respond_to do |format|
    if @patient.update_attributes(params[:patient])
      format.html { redirect_to @patient, notice: 'Patient was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "edit" }
      format.json { render json: @patient.errors, status: :unprocessable_entity }
    end
  end
end

还有这样的形式:

<%= form_for @patient do |f| %>
  <%= f.fields_for ([@patient, @patient.treatments.build]) do |tf| %>
    <%= render 'treatment_form', form: tf  %>
  <% end %>
  <%= f.fields_for ([@patient, @patient.treatments.build]) do |tf| %>
    <%= render 'treatment_form', form: tf  %>
  <% end %>
  <%= f.submit %>
<% end %>

所以我不知道我必须向患者控制器添加什么?

我像@JimLim 推荐的那样更改了我的代码,但我得到了同样的错误:

 ActiveRecord::UnknownAttributeError in PatientsController#update

 unknown attribute: treatment

{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"OPuS9Mmk3guiV20nkw5OaPUFyjVow49H+MMxY37O0r0=",
 "patient"=>{"treatment"=>{"category_id"=>"9",
 "content"=>"dsfsdf",
"day"=>"2013-07-21"}},
"commit"=>"Update Patient",
 "id"=>"9"}

【问题讨论】:

  • 您的患者模型是什么样的?
  • attr_accessible :alter, :nachnahme, :ort, :strasse, :telefon, :vorname, :treatment_attributes, :treatment has_many :treatments has_many :categories, :through => :treatments has_many :paintings, :通过 => :treatments accepted_nested_attributes_for :treatments
  • 你好。 “治疗”不应该在 attr_accessible 中。这不是患者的属性;这完全是另一个模型。您有treatment_attributes(可能需要更改为treatment_attributes,不确定),因为您说您接受治疗的属性,但治疗本身不是患者模型的一部分。如果你删除它,它可能会解决问题。无论如何,它可能应该被删除。
  • 能否请您在 Rails 日志中包含 POST 请求的内容?
  • 你解决了这个问题吗?如果没有,我会从 patient.rb 的 attr_accessible 列表中删除 :treatment。它不应该在那里。只有 :treatments_attributes 应该。我认为这至少可能会导致问题。

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


【解决方案1】:

这些参数包括一个treatment 键,它不是您的 Patient 模型中的属性。如果是这种情况,你需要

  1. 更改表单,使键为treatments 而不是treatment,并且
  2. 在您的患者模型中添加 #accepts_nested_attribute_for

例如,

<%= f.fields_for :treatments, @patient.treatments.build do |tf| %>
  <%= render 'treatment_form', form: tf  %>
<% end %>

class Patient
  accepts_nested_attributes_for :treatments
end

documentation for fields_for 有更详细的解释。

【讨论】:

  • 谢谢。我的猜测是正确的,答案仍然适用。如果它对你有用,请接受我的回答。
猜你喜欢
  • 2015-10-04
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多