rails 3.2.13,update_attributes错误

时间:2013-12-18 05:27:23

标签: ruby-on-rails ruby

更新时,我收到了这样的错误。

Couldn't find PropertyAcceptanceCriterion with ID=14 for Property with ID=1

关闭复选框时会发生此错误,并更新(保存)。

请教我这个理由,接下来该怎么做,

模型定义是

class PropertyAcceptance < ActiveRecord::Base
  belongs_to :property
  belongs_to :property_acceptance_criterion
end

class PropertyAcceptanceCriterion < ActiveRecord::Base
  attr_accessible :name
  has_many :property_acceptances, dependent: :destroy
  has_many :properties, through: :property_acceptances
end

class Property < ActiveRecord::Base
  attr_accessible :rent
  attr_accessible :room_no
  attr_accessible :property_acceptance_criterions_attributes
  attr_accessible :property_acceptance_criterion_ids
  has_many :property_acceptances, dependent: :destroy
  has_many :property_acceptance_criterions, through: :property_acceptances
  accepts_nested_attributes_for :property_acceptance_criterions, reject_if: lambda { |a| a[:name].blank? }
end

视图定义是

= simple_nested_form_for @property do |f|
  = f.input :room_no, input_html: {class: 'span2'}
  = f.input :rent, input_html: {class: 'span2'}
  = f.association :property_acceptance_criterions, as: :check_boxes
  = f.simple_fields_for :property_acceptance_criterions do |c|
    = c.input :name, label: "add for #{t('activerecord.attributes.property.property_acceptance_criterions')}" if c.object.new_record?

控制器定义是

class Insurance::PropertiesController < Insurance::InsuranceController
  def new
    @property.property_acceptance_criterions.build
  end
  def create
    @property.attributes = params[:property]
    if @property.save
      redirect_to @property, success: t('activerecord.flash.property.actions.create.success')
    else
      render :new
    end
  end
  def edit
    @property.property_acceptance_criterions.build
  end
  def update
    if @property.update_attributes(params[:property]) # ← error occur
      redirect_to @property, success: t('activerecord.flash.property.actions.update.success')
    else
      render :edit
    end
  end
end

错误是

Couldn't find PropertyAcceptanceCriterion with ID=14 for Property with ID=1

params是

{"utf8"=>"✓",
  "_method"=>"put",
  "authenticity_token"=>"+Zx7l7mAbX12PSO873x5NDxNOIeEe6bEDEdVnys+a98=",
  "property"=>{
  "room_no"=>"000",
  "rent"=>"80000",
  "property_acceptance_criterion_ids"=>["13", "25", ""],
  "property_acceptance_criterions_attributes"=>{
    "0"=>{"id"=>"13"}, "1"=>{"id"=>"14"}, "2"=>{"id"=>"25"}, "3"=>{"name"=>""}
  },
  "commit"=>"update",
  "id"=>"1"}

1 个答案:

答案 0 :(得分:0)

在编辑中尝试使用此功能

def edit
  @property = Property.find(params[:id])
end

请将此代码添加到Controller

  before_filter :load_property, only: [:edit, :update]
  before_filter :new_property, only: [:new, :create]

  ......

  private

  def load_property
    @property = Property.find(params[:id])
  end

  def new_property
    @property = Property.new
  end

发生错误,然后添加您的指示。