【发布时间】:2015-04-02 21:56:47
【问题描述】:
我有一个表单,它应该从提交表单时所在的select 标记中删除option。但是,即使表单能够在我的 UnitTypes 控制器中调用正确的 destroy 操作,我仍然会收到此错误:
ActiveRecord::RecordNotFound in UnitTypesController#destroy
Couldn't find UnitType with 'id'=
似乎我的form_for 中的值没有将值传递给控制器。
我尝试了许多不同的方法来让它工作,但似乎form_for 和:method => :delete 一起使用效果不佳。
我尝试为表单传递垃圾字符串值以“满足”url 对参数的需求,但这也没有奏效。
这是我所拥有的:
路线:
resources :unit_types
表格
.panel.panel-default
= form_for @unitType, :html => { :method => :delete, remote: true } do |f|
.panel-heading
%strong Remove Unit Type
.panel-body
= f.select :id, options_from_collection_for_select(UnitType.all, "id", "name"), { :prompt => "Delete..." }, class: "form-control unit-type-select", id: "remove-unit-type-field"
.panel-footer
= f.submit "Remove", :id => "remove-unit-type", :class => "btn btn-default"
UnitTypesController
class UnitTypesController < ApplicationController
def create
@unitType = UnitType.new(unit_type_params)
if @unitType.save
respond_to do |format|
format.js
end
else
flash.now[:alert] = "Failed to create new unit type."
end
end
def destroy
@unitType = UnitType.find(params[:id])
if @unitType.destroy
respond_to :js
else
flash.now[:alert] = "There was an error trying to delete the unit type."
end
end
private def unit_type_params
params.require(:unit_type).permit(:name)
end
end
【问题讨论】:
-
您的表单发送 params[: unit_type][:id] 而 params[:id] 为 nil。你不需要修改unit_type_params,但你应该做
@ unitType = UnitType.find(params[:unit_type][:id]) -
这样做比强参数有优势吗?
标签: ruby-on-rails forms ruby-on-rails-4