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

Ruby on Rails购物车功能问题:按钮点击后无法跳转至购物车页面

问题描述

我在小组项目里开发网站的「加入购物车」功能,需求是点击按钮后把商品加入购物车,同时跳转到购物车页面展示已添加的商品。现在按钮已经做出来,但点击后不会跳转,还停留在商品页面。


相关代码

Cart 控制器

class CartController < ApplicationController
  def index
    @cart = Prebuilt.all
    render :index
  end

  def show
    @cart = current_cart
   end

  def add_to_cart
    current_cart.add_item(params[:prebuilt_id])
  end

end

Cart 模型

class Cart < ApplicationRecord
  has_many :items

  def add_item(prebuilt_id)
    item = items.where('prebuilt_id', prebuilt_id.first)
    save
  end

end

Item 模型

class Item < ApplicationRecord
  belongs_to :cart
end

路由配置

# root to: redirect('/cart')

  get 'cart', to: 'cart#index', as: 'cart';

  post '/add_to_cart/:prebuilt_id' => 'cart#add_to_cart', :as => 'add_to_cart'

  get 'checkout', to: 'pages#checkout', as: 'checkout';

  get 'confirm', to: 'pages#confirm', as: 'confirm';

Seeds 数据

prebuilt1 = Prebuilt.create!(
  name: "Alfred's Artistic Jet",
  description: "Designed by Alfred",
  manufacturer: "Boeing",
  color: "Mixed",
  size: "Large",
  price: 2999999
)

prebuilt2 = Prebuilt.create!(
  name: "Brittany's Barbie Jet",
  description: "Designed by Brittany",
  manufacturer: "Boeing",
  color: "Pink",
  size: "Large",
  price: 4499999
)

prebuilt3 = Prebuilt.create!(
  name: "Peter's Prehistoric Jet",
  description: "Designed by Peter",
  manufacturer: "Airbus",
  color: "Blue",
  size: "Small",
  price: 7999999
)

prebuilt4 = Prebuilt.create!(
  name: "Tianna's Tractor-Themed Jet",
  description: "Designed by Tianna",
  manufacturer: "Airbus",
  color: "Mixed",
  size: "Large",
  price: 1999999
)

商品页面视图

<table class="table table-striped table-hover">

  <thead class="table-dark">
    <tr>
      <th>Name</th>
      <th>Description</th>
      <th>Manufacturer</th>
      <th>Color</th>
      <th>Size</th>
      <th>Price</th>
      <th></th>
    </tr>
  </thead>

  <tbody>
    <% @prebuilts.each do |prebuilt| %>
      <tr>
        <td><%= prebuilt.name %></td>
        <td><%= prebuilt.description %></td>
        <td><%= prebuilt.description %></td>
        <td><%= prebuilt.manufacturer %></td>
        <td><%= prebuilt.color %></td>
        <td><%= prebuilt.size %></td>
        <td><%= prebuilt.price %></td>
        <td class="text-nowrap">
          <%= link_to 'show', prebuilt_path(prebuilt), class: 'btn btn-sm btn-outline-secondary' %>
          <td><%= button_to "add to cart", cart_path(:prebuilt_id => prebuilt), method: :post %></td>
        </td>
      </tr>
    <% end %>
  </tbody>

</table>

购物车页面视图

<table id="line_items">
  <tr>
    <th>Product</th>
    <th>Qty</th>
    <th class="price">Unit Price</th>
    <th class="price">Full Price</th>
  </tr>

  <% for item in @cart %>
    <tr class="<%= cycle :odd, :even %>
       <td><%=h item.name %></td>
    </tr>
   <% end %>
  </tr>
</table>

问题修复步骤

1. 修正「加入购物车」按钮的路由与HTML结构

当前按钮错误指向了购物车列表的GET路由,需要替换为add_to_cart的POST路由,同时修复嵌套<td>的结构错误:

<td class="text-nowrap">
  <%= link_to 'show', prebuilt_path(prebuilt), class: 'btn btn-sm btn-outline-secondary' %>
  <%= button_to "add to cart", add_to_cart_path(prebuilt.id), method: :post, class: 'btn btn-sm btn-outline-primary' %>
</td>

2. 给add_to_cart方法添加跳转逻辑

控制器方法执行完添加操作后没有跳转,导致页面停留,补充重定向代码:

def add_to_cart
  current_cart.add_item(params[:prebuilt_id])
  redirect_to cart_path # 跳转到购物车页面
end

3. 修复Cart模型的add_item方法逻辑

当前where语法错误,且未处理商品重复添加的情况,修正如下:

def add_item(prebuilt_id)
  # 查找或初始化对应商品项
  item = items.find_or_initialize_by(prebuilt_id: prebuilt_id)
  # 如果需要支持数量累加,添加:item.quantity += 1; item.save
  save
end

4. 修正购物车页面的控制器与视图逻辑

首先修改Cart控制器的index方法,正确获取当前购物车:

def index
  @cart = current_cart
end

然后修复购物车页面的循环逻辑,遍历购物车的items并补充缺失的列与闭合标签:

<table id="line_items">
  <tr>
    <th>Product</th>
    <th>Qty</th>
    <th class="price">Unit Price</th>
    <th class="price">Full Price</th>
  </tr>

  <% @cart.items.each do |item| %>
    <tr class="<%= cycle :odd, :even %>">
       <td><%= item.prebuilt.name %></td>
       <td>1</td> <!-- 若有数量字段,替换为item.quantity -->
       <td><%= number_to_currency(item.prebuilt.price) %></td>
       <td><%= number_to_currency(item.prebuilt.price) %></td>
    </tr>
   <% end %>
</table>

5. 完善Item模型的关联

Item模型需要关联Prebuilt才能显示商品信息,同时生成对应迁移:

class Item < ApplicationRecord
  belongs_to :cart
  belongs_to :prebuilt # 新增关联
end

执行迁移命令:

rails generate migration AddPrebuiltIdToItems prebuilt:references
rails db:migrate

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:30:58