Rails嵌套表单未经许可的参数

时间:2016-06-16 11:13:05

标签: ruby-on-rails strong-parameters

当我创建或编辑产品时,由于
,我的merchant_product_detail不会被创建或编辑 未经许可的参数:merchant_id 。但其他像id和price都可以通过强参数,只有merchant_id无法通过它。请帮助我为什么我的merchant_id在这种情况下不允许?

paramsbinding.pry模式

返回
"product"=>
      {"name"=>"fewrgvers",
       "description"=>"",
       "product_categories_attributes"=>{"0"=>{"id"=>""}},
       "merchant_product_details_attributes"=>
        {"0"=>{"merchant_id"=>["2"], "id"=>"", "price"=>"123"}}
    "

product_params返回

    Unpermitted parameter: merchant_id
    => {"name"=>"fewrgvers",
     "description"=>"",
     "merchant_product_details_attributes"=>{"0"=>{"id"=>"", "price"=>""}}

product.rb

has_many :merchant_product_details
accepts_nested_attributes_for :merchant_product_details, reject_if: proc { |attributes| attributes['merchant_id'].blank? }
has_many :merchants, through: :merchant_product_details

merchant.rb

has_many :merchant_product_details
has_many :products, through: :merchant_product_details
accepts_nested_attributes_for :merchant_product_details

merchant_product_detail.rb

belongs_to :product
belongs_to :merchant

product_controller.rb

 def new
    @product = Product.new
    @product.merchant_product_details.build
end

def create
    @product = Product.new(product_params)
    respond_to do |format|
      if @product.save
        format.html { redirect_to root_path, notice: 'Product was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end
end

def update
    respond_to do |format|
      if @product.update_attributes(product_params)
        format.html { redirect_to root_path, notice: 'Product was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
end


params.require(:product).permit(:name, :description, 
      merchant_product_details_attributes: [:id, :merchant_id, :price]

_form.html.erb

<%= form_for(@product, :url => path, html: { class: "form-horizontal", role: "form" }) do |f| %>
<%= f.fields_for :merchant_product_details do |builder| %>
    <div class="form-group row">
      <%= builder.label :merchant_id, class: "col-md-2 control-label" %>
      <div class="col-md-8">
        <%= builder.select :merchant_id, Merchant.all.collect {|x| [x.name, x.id]}, {include_hidden: false} ,prompt: "Select something", multiple: true, class: "select2" %>
        <%= builder.hidden_field :id %><br>
              <%= builder.label :price %>
        <%= builder.number_field :price %>
      </div>
<% end %>

1 个答案:

答案 0 :(得分:1)

问题是multiple: true的表单字段中的merchant_id。这意味着param将是一个数组,因为它可能是多个商家ID。

如果这是您想要的,那么我建议将名称更改为merchant_ids并允许这样的数组:

params.require(:product).permit(:name, :description, 
  merchant_product_details_attributes: [:id, :price, merchant_ids: []])

看一下你的模型关系,我认为你只想拥有一个id,在这种情况下,它应该足以删除select中的multiple: true

<%= builder.select :merchant_id, Merchant.all.collect {|x| [x.name, x.id]}, {include_hidden: false}, prompt: "Select something", class: "select2" %>