无法使用嵌套表单批量分配属性

时间:2013-04-24 12:50:08

标签: ruby-on-rails nested-form-for

我有2个表格,订单表格和产品表格。我希望产品形式在订单下。我收到此错误:无法批量分配受保护的属性:products_attributes。

这是我的订单型号

  

class Order<的ActiveRecord :: Base的     attr_accessible:comments,:due_date,:order_type,:print_color,:print_location,:title,   :产品
   验证:order_type,:due_date,:print_color,:title,:presence =>真正
   验证:title,:uniqueness =>真正
    has_many:产品
    accepts_nested_attributes_for:products,:allow_destroy =>真的     端

产品型号

  

类产品<的ActiveRecord :: Base的
    attr_accessible:数量
    has_one:订单
  端

命令控制器:

>class OrdersController < ApplicationController
  # GET /orders
  # GET /orders.json
  def index
    @orders = Order.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @orders }
    end
  end

  # GET /orders/1
  # GET /orders/1.json
  def show
    @order = Order.find(params[:id])
    @products = @order.products.find(:all)

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @order }
    end
  end

  # GET /orders/new
  # GET /orders/new.json
  def new
    @order = Order.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
    end
  end

  # GET /orders/1/edit
  def edit
    @order = Order.find(params[:id])
  end

  # POST /orders
  # POST /orders.json
  def create
    @order = Order.new(params[:order])
    respond_to do |format|
      if @order.save
        format.html { redirect_to @order, notice: 'Order was successfully created.' }
        format.json { render json: @order, status: :created, location: @order }
      else
        format.html { render action: "new" }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /orders/1
  # PUT /orders/1.json
  def update
    @order = Order.find(params[:id])

    respond_to do |format|
      if @order.update_attributes(params[:order])
        format.html { redirect_to @order, notice: 'Order was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
  end
  # DELETE /orders/1
  # DELETE /orders/1.json
  def destroy
    @order = Order.find(params[:id])
    @order.destroy

    respond_to do |format|
      format.html { redirect_to orders_url }
      format.json { head :no_content }
    end
  end
end

任何帮助将不胜感激!提前谢谢。

1 个答案:

答案 0 :(得分:0)

替换:

 attr_accessible ..., :products

使用:

 attr_accessible ..., :products_attributes