2016-06-08 28 views
0

我需要将阵列保存到我的order.rb模型中。导轨4不允许的参数:产品

数组是: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 

我的订单PARAMS。

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

我想两种不同的方式permite的产品,这就是为什么你会看到上面

两个数组请大家看看,我没有使用somethig,如:

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

,因为如果我用我的错误:

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

谢谢。

回答

1

你需要做的是在Rails的方式...

在模型/ 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”}]}}

+0

嗨@Leantraxxx,我加入了relathionship订购模式。 我不明白“products_attributes”,为什么我需要把它放到“products_controller”中。对不起这部分,但我不明白。 “:listing”,“product_attributes:[]” 谢谢 –

+0

其实。如果我在我的“orders_controller”中使用:params.require,我得到错误:ActionController :: ParameterMissing - param丢失或值为空:order: –

+0

对不起'orders_controller' – Leantraxxx