【问题标题】:Rails 4: Strong parameters + nested attributes + multiple selectRails 4:强参数+嵌套属性+多选
【发布时间】:2016-02-13 00:29:31
【问题描述】:

我有一个名为TaxCategory 的模型,即has_many :tax_ratesaccepts_nested_attributes_for :tax_rates, reject_if: :all_blank, allow_destroy: true

TaxRates 本身就是一个模型,其中包括has_and_belongs_to_many :countries

这些关系运行良好,我可以通过控制台添加和删除国家/地区。

但是,我有一个包含 fields_for :tax_rates do |g| 的 TaxCategory 表单。

在里面,我有一个

g.select :country_ids, Country.collect{|c| [c.name, c.id]}, {multiple: true}, {}

它提交给tax_categories控制器,它使用以下代码更新TaxCategory

class TaxCategoriesController
  before_action :set_tax_category, only: [:show, :edit, :update, :destroy]

 ...*snip*...

  def update
     respond_to do |format|
      if @tax_category.update(tax_category_params)
        format.html { redirect_to [:dashboard,  @tax_category], notice: 'Tax Category was successfully updated.' }
        format.json { render :show, status: :ok, location: @tax_category }
      else
        format.html { render :edit }
        format.json { render json: @tax_category.errors, status: :unprocessable_entity }
      end
    end

    private

  def set_tax_category
    @tax_category = TaxCategory.find(params[:id])
  end

  def tax_category_params
    params.require(:tax_category).permit(:name, tax_rates_attributes:[:id, :rate,{country_ids: []}, :_destroy])
  end


end

但是,这不起作用;提交表单时,只保存第一个 Country,Rails 命令行显示 Unpermitted parameter: country_ids 消息。

我认为这是由params.permit引起的问题,但我不明白我做错了什么。

出了什么问题,我该如何解决?

【问题讨论】:

    标签: ruby-on-rails nested-forms nested-attributes strong-parameters


    【解决方案1】:

    更新

    我想我找到了问题所在。您的示例参数说country_ids: 1,它应该是country_ids: [1],因为它应该是一个数组/多个值。

    将以下内容更新为:

    g.select :country_ids, Country.collect{|c| [c.name, c.id]}, {}, {multiple: true}
    
    未经许可的参数错误感觉很可能是 `tax_category_params` 是问题所在。你能试试这个 def tax_category_params params.require(:tax_category).permit(:name, tax_rates_attributes: [:id, :rate, country_ids: [], :_destroy]) 结尾

    【讨论】:

    • 这被证明是无效的 Ruby 语法,因为解释器无法自行确定如何将其包装为散列(我认为这与 named parameters 有关。将其放在结束,像这样:params.require(:tax_category).permit(:name, tax_rates_attributes:[:id, :rate, :_destroy, country_ids: []]) 不会产生语法错误,但仍然有与上面完全相同的结果,例如Unpermitted parameter: country_ids
    • 嗯。你能puts params 在更新操作中吗?我很想知道请求的实际参数。 tax_category_params 在我看来还不错。
    • 发送到请求的参数是:{"utf8"=>"✓", "authenticity_token"=>"424242VHWTNtNTDzPhV9U1aV+t1d2VBx9+heakYGSyozK+MkYvCPc3JJZIB+zSXn2vsqucZQ/P2J8F8ale2Yw==", "tax_category"=>{"name"=>"General", "tax_rates_attributes"=>{"0"=>{"rate"=>"21.0", "country_ids"=>"1", "_destroy"=>"false", "id"=>"1"}, "1"=>{"rate"=>"10.0", "country_ids"=>"2,3,4", "_destroy"=>"false", "id"=>"3"}}}, "button"=>"", "id"=>"1"},我觉得很好。
    • 确实如此。这似乎是由我的表单生成器引起的,它返回country_ids: "1,2,3,4,5" 而不是country_ids: ["1", "2", "3", "4", "5"]。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多