Rails4: How to append fields that are not white-listed (strong parameters)

时间:2015-11-12 11:59:50

标签: ruby-on-rails-4

I am not sure how to put this. Someone may already asked this question!

I have an order table and it has product_details column. However, when user submit the order form it only gets user's name and address. I want to manually add product details when it saves the data.

My order controller

    def create
      @neworder = Order.new(order_params)
      if @neworder.save
        redirect_to root_url, notice: ""
      else
        render "new"
      end
    end

   private
    def order_params
      params.require(:order).permit(:name,:address)
    end

If I white-list product_details field then I guess it will be open to "mass assignment" or not?
params.require(:order).permit(:name,:address, :product_detail)

1 个答案:

答案 0 :(得分:0)

如果您的“product_details”正在通过表单提交,那么您需要将其添加到许可白名单中,如下所示:

def order_params
  params.require(:order).permit(:name,:address, :product_details)
end

但是,我认为通过“手动追加”你的意思是在控制器中设置该属性。如果是这种情况,那么你不应该将它添加到许可证列表中,因为它将允许大量分配该字段 - 这可能是你不想要的。

您需要的是更改您的创建操作:

def create
  @neworder = Order.new(order_params)
  @neworder.product_details = "test"
  if @neworder.save
    redirect_to root_url, notice: ""
  else
    render "new"
  end
end