2015-04-02 24 views
0

我有一个表格,应该从select标记中删除option表单,该表单在提交时位于该表单中。然而,尽管形式能够调用正确的destroy行动,我UnitTypes控制器,我不断收到此错误:form_for不会将选择字段的值传递给控制器​​? Rails 4

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 
+0

您的表单发送params [:unit_type] [:id],params [:id]为零。你不需要修改unit_type_params,但你应该这样做'@ unitType = UnitType.find(params [:unit_type] [:id])' – cristian 2015-04-02 22:06:03

+0

在强参数上这样做有没有优势? – 2015-04-02 22:13:16

回答

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也可能有另一个问题。

+0

完美!我很惊讶,在这两天里我找不到Google的回答。非常感谢,这让我很开心。 – 2015-04-02 22:08:39

+0

第一次,我花了几天的时间:)不客气。 – 2015-04-02 22:10:46

相关问题