如何设置表单提交至正确路径?产品变体提交关联报错问题
解决Rails嵌套资源表单提交路径问题
嗨,我来帮你搞定这个问题!你遇到的核心问题是表单没有关联父产品资源,导致Rails生成了非嵌套的路由路径。咱们一步步来修正:
关键修改:给form_with传递嵌套资源数组
你的路由里已经把variants嵌套在products下了,所以在表单里需要同时指定父产品和子变体,这样Rails才会生成正确的嵌套路径。把原来的表单代码改成这样:
<%= form_with(model: [@product, variant], local: true) do |form| %>
确保控制器里正确赋值父产品
要让这个表单正常工作,你需要在VariantsController的对应动作(比如edit、update)里,先找到父产品,再找到对应的变体:
# app/controllers/variants_controller.rb def edit @product = Product.find(params[:product_id]) @variant = @product.variants.find(params[:id]) end def update @product = Product.find(params[:product_id]) @variant = @product.variants.find(params[:id]) # 后续的更新逻辑... end
验证路由是否正确
你可以在终端运行rails routes,找到类似这样的路由条目,确认嵌套路径存在:
product_variant PUT /products/:product_id/variants/:id(.:format) variants#update
额外提示:新建变体的情况
如果是新建变体的表单,同样需要传递父产品和新的变体对象:
<%= form_with(model: [@product, Variant.new], local: true) do |form| %>
这样会生成POST /products/:product_id/variants的正确路径。
为什么原来的写法不行?因为你只传了variant作为model参数,Rails会默认使用最外层的resources :variants路由,而不是你需要的嵌套在products下的那个版本。通过传递[@product, variant]数组,Rails就知道要使用嵌套路由规则啦!
内容的提问来源于stack exchange,提问作者spacerobot
相关产品推荐
相关产品推荐

