我有一个模型
User
和StockShipment
。
我正在尝试通过 StockShipment
new
操作为我的用户创建各种 StockShipment。
为此,我在我的用户模型中使用:
accepts_nested_attributes_for :stock_shipments, reject_if: :all_blank, allow_destroy: true
在我的stockshipments/new.html.erb
<%= form_with model: [@user, @stock_shipment] do |form| %>
<%= form.fields_for :stock_shipments, @user.stock_shipments.build do |shipment_form| %>
<%= render 'shared/shipment_fields', form: shipment_form, locals: { user: current_user, user_stock: @user_stock } %>
<% end %>
在我的库存发货控制器中:
def new
@user = current_user
@stock_shipment = StockShipment.new
@user.stock_shipments.build
end
def create
@user = current_user
@user_stock = UserStock.find(params[:stock_shipment][:user_stock_id])
@stock_shipment = @user.stock_shipments.build(stock_shipments_params)
if @stock_shipment.save
ShipmentNotificationMailer.new_shipment_notification(@stock_shipment).deliver_later
redirect_to user_stock_shipments_path(current_user), status: :see_other
else
puts @stock_shipment.errors.full_messages.inspect
end
end
最后,我有强大的参数来接受嵌套属性:
def stock_shipments_params
params.require(:stock_shipment).permit(
:country, :phone, :email,
:name, :quantity, :address, :city, :province, :postalcode, :surname, :user_id, :campaign_id, :gift_selection_id, :delivery_date, :stock_variation, :description, :user_stock_id,
stock_shipments_attributes: [:id, :country, :phone, :email, :name, :quantity, :address, :city, :province, :postalcode, :surname, :user_id, :campaign_id, :gift_selection_id, :delivery_date, :stock_variation, :description, :user_stock_id, :_destroy]
)
end
我一直收到以下错误:
Unpermitted parameter: :stock_shipments.
我的参数正在传递:
Started POST "/users/388/stock_shipments?locale=es" for ::1 at 2023-12-17 13:58:03 +0100
13:58:03 web.1 | Processing by StockShipmentsController#create as TURBO_STREAM
13:58:03 web.1 | Parameters: {"authenticity_token"=>"[FILTERED]", "stock_shipment"=>{"stock_shipments"=>{"quantity"=>"1", "name"=>"asdf", "surname"=>"asdf", "address"=>"sadf", "postalcode"=>"213", "city"=>"asdf", "province"=>"asdf", "country"=>"bg", "phone"=>"234", "email"=>"[email protected]", "delivery_date"=>"2023-12-20", "user_id"=>"388", "_destroy"=>"false"}, "user_stock_id"=>"84", "user_id"=>"388"}, "user"=>{"stock_shipments_attributes"=>{"1702817879"=>{"quantity"=>"30", "name"=>"María", "surname"=>"Jisd", "address"=>"Cadsf", "postalcode"=>"238", "city"=>"Madrid", "province"=>"adsf", "country"=>"es", "phone"=>"645455555", "email"=>"[email protected]", "delivery_date"=>"2023-12-20", "user_id"=>"388", "_destroy"=>"false"}}}, "commit"=>"Confirmar envíos", "locale"=>"es", "user_id"=>"388"}
您没有显示部分内容,这是一些问题所在的地方,但是您将
user_stock: @user_stock
发送到其中,但 @user_stock
尚未在任何地方定义。
大多数情况下,您的
form_with
和 fields_for
通话中都会有很多不必要的垃圾。您应该遵循嵌套表单指南以获得乐趣和利润。