form_for不会将select字段的值传递给控制器​​? Rails 4

时间:2015-04-02 21:56:48

标签: ruby-on-rails forms ruby-on-rails-4

我有一个表单,该表单应该在提交表单时从option标记中删除select。但是,即使表单能够在我的destroy控制器中调用正确的UnitTypes操作,我仍然会收到此错误:

ActiveRecord::RecordNotFound in UnitTypesController#destroy

Couldn't find UnitType with 'id'=

出现form_for的值未将值传递给控制器​​。

我尝试了许多不同的方法来实现这一点,但似乎form_for:method => :delete的使用并不能很好地发挥作用。

我尝试将表单的垃圾字符串值传递给"请"网址对参数的需求,但这也没有用。

以下是我所拥有的:

路线: 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

1 个答案:

答案 0 :(得分:1)

您应该通过unit_type_params

引用参数
def destroy
    @unitType = UnitType.find(unit_type_params[:id]) #change here
    # ...
end

private def unit_type_params
    params.require(:unit_type).permit(:id, :name) # and here
end

这是因为Rails strong parameters

如果仍然无法正常工作,请告诉我。 params可能还有其他问题。