Rails 4:强参数+嵌套属性+多选

时间:2016-02-13 00:29:32

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

我有一个名为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

然而,这确实工作;提交表单时,只保存第一个国家/地区,Rails命令行显示Unpermitted parameter: country_ids消息。

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

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

1 个答案:

答案 0 :(得分:1)

<强>更新

我想我发现了这个问题。您的示例参数说country_ids: 1,其中应该是country_ids: [1],因为它应该是数组/多个值。

将以下内容更新为:

g.select :country_ids, Country.collect{|c| [c.name, c.id]}, {}, {multiple: true}
<德尔> 不允许的Params错误感觉很可能`tax_category_params`是问题所在。你能试试吗?     def tax_category_params       params.require(:tax_category).permit(:name,tax_rates_attributes:[:id,:rate,country_ids:[],:_ destroy])     结束
相关问题