UnknownAttributeError in Controller

ⅰ亾dé卋堺 提交于 2020-01-17 08:08:09

问题


With the help of @Sasha i created an nested form for treatments in patients:

Now i get this error:

UnknownAttributeError in PatientsController#update

unknown attribute: treatment

My patients update controller actually looks like this:

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

And the form like this:

<%= 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 %>

So i have no clue what i have to add to my patients controller?

I changed my code like @JimLim recomended, but i get the same error:

 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"}

回答1:


The parameters include a treatment key that is not an attribute in your Patient model. If that is the case, you need to

  1. change the form such that the key is treatments instead of treatment, and
  2. add #accepts_nested_attribute_for in your Patient model.

For example,

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

class Patient
  accepts_nested_attributes_for :treatments
end

A more detailed explanation is available in the documentation for fields_for.



来源:https://stackoverflow.com/questions/17776091/unknownattributeerror-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!