2016-06-08 52 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