【问题标题】:form_for won't pass value of select field to controller? Rails 4form_for 不会将选择字段的值传递给控制器​​?导轨 4
【发布时间】: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


【解决方案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 也可能存在另一个问题。

【讨论】:

  • 完美!我很惊讶在过去的两天里我无法通过谷歌找到答案。非常感谢,这让我很开心。
  • 第一次,我也花了几天时间:)不客气。
猜你喜欢
  • 1970-01-01
  • 2015-10-11
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 2018-01-08
相关资源
最近更新 更多