You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Spree引擎外实现添加至购物车的Link Button

解决Spree引擎外部视图添加直接加入购物车按钮的问题

问题根源

你之前的代码错误在于用link_to发起GET请求跳转至展示类路径(spree.cart_path或spree.product_path),但Spree的商品加入购物车功能需要POST请求到spree.populate_orders_path接口,同时必须携带商品变体ID(variant_id)和购买数量(quantity)参数,否则无法将商品添加到购物车,导致跳转至空购物车页面。

解决方案

结合你现有表单结构,有两种可行修改方式:

方式一:利用现有表单提交(推荐)

你已经在form_for :order, url: spree.populate_orders_path表单内,且表单已包含variant_id隐藏字段和数量输入框,只需将错误的link_to替换为表单提交按钮即可:

将自定义按钮代码:

<%= link_to t("cart_info.add_to_cart"), spree.product_path(@spree_product), class: "button button-rounded button-flat-action", style: "margin-top: 10px", type: :submit %>

修改为:

<%= f.submit t("cart_info.add_to_cart"), class: "button button-rounded button-flat-action", style: "margin-top: 10px" %>

点击该按钮会触发表单的POST请求,自动携带variant_id和quantity参数,完成商品添加后会直接跳转至用户购物车页面。

方式二:用link_to发起POST请求(无需依赖表单)

如果不想依赖现有表单,可直接用link_to发起POST请求,手动传递必要参数:

<%= link_to t("cart_info.add_to_cart"), spree.populate_orders_path, 
            method: :post, 
            params: { variant_id: @spree_product.master.id, quantity: 1 },
            class: "button button-rounded button-flat-action", 
            style: "margin-top: 10px" %>

注意:Rails会自动处理CSRF令牌(需确保页面包含Rails默认的CSRF meta标签),若遇到CSRF验证错误,可在params中添加authenticity_token: form_authenticity_token参数。

额外说明

  • spree.cart_path是购物车的展示页面接口(GET请求),仅用于查看购物车,无法添加商品;
  • spree.product_path是商品详情页路径,点击后只会跳转至商品详情,不会触发添加购物车操作。

内容的提问来源于stack exchange,提问作者Takalani Madau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 22:24:20