Rails 4 不允许的参数:产品

Rails 4 Unpermitted parameters: products

我需要将数组保存到我的 order.rb 模型中。

数组为:params[:products]

数组给我这样的东西:

[{"'name'"=>"31 DVIE33N - Traditional ", "'id'"=>"2", "'quantity'"=>"1", "'accessory'"=>{"'id'"=>"7", "'name'"=>"31-SK4BLANKD-2"}}]

创建操作:

def create
    @order = Order.new(order_params)

    respond_to do |format|
      if @order.save
        format.html { redirect_to admin_orders_path(@order), notice: 'Order was successfully created.' }
        format.json { render :show, status: :created, location: @order }
      else
        format.html { render :new }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
 end

我的订单参数。

private
    def order_params
      params.permit({:products=>[], products:[])
    end

我正在尝试两种不同的方式来允许产品,这就是为什么你会在上面看到两个数组

请看一下,我没有使用像这样的东西:

params.require(:order).permit(:products => []}, :products=>[])

因为如果我使用它,我会收到错误消息:

ActionController::ParameterMissing - param is missing or the value is empty: order:

谢谢。

您需要以 Rails 的方式进行...

在models/order.rb

class Order < ActiveRecord::Base
  has_many :products
  accepts_nested_attributes_for :products, allow_destroy: true
end

在orders_controller.rb

def order_params
  params.require(:order).permit(products_attributes: [:name, :etc])
end

products_attributes数组中你可以传递你想要允许的产品属性。

您需要像这样发送 product_attributes{“order”=>{“products_attributes"=>[{“name”=>”product 1”}, {“name”=>”product 2”}]}}