保华的Rails学习笔记

将商品加入到购物车

step1、建立加入购物车的 action

在product的show页面,加入一个"加入购物车"按钮
1)app/views/products/show.html.erb加入下边的代码

<%= link_to("加入购物车", add_to_cart_product_path(@product), :method => :post, :class => "btn btn-primary btn-lg btn-danger") %>

2)然后修改 app/controllers/products_controller.rb 加入 add_to_cart action

def add_to_cart
    @product = Product.find(params[:id])
    current_cart.add_product_to_cart(@product)
    flash[:notice] = "成功加入购物车"
    redirect_to :back
  
  end

3)修改 config/routes.rb,把add_to_cart的path添加上去

resources :products do
    member do
      post :add_to_cart
    end
  end

step2 购物车设计1

1)产生cart与cart_item两个model

rails g model cart
rails g model cart_item

2)修改cart_item的migration

class CreateCartItems < ActiveRecord::Migration[5.0]
  def change
    create_table :cart_items do |t|
      t.integer :cart_id
      t.integer :product_id
      t.integer :quantity
      t.timestamps
    end
  end
end

里边有cart_id与product_id,是为了cart_item与cart和product能够建立关联

然后执行rake db:migrate
3)修改app/models/cart.rb

class Cart < ApplicationRecord
  has_many :cart_items
  has_many :products, through: :cart_items, source: :product
end

cart与cart_item是一对多的关系,一个cart里边,可以有多个cart_item(一个item对应produc名称与quantity)
cart与product是多对多的关系,这里用了has_many :products,是通过cart_item来实现的,这样cart.products可以捞出购物车里边的product信息
4)修改CartItem这个model(app/models/cart_item.rb)

class CartItem < ApplicationRecord
  belongs_to :cart
  belongs_to :product
end

5)实作add_to_product

app/models/cart.rb
class Cart < ApplicationRecord
  has_many :cart_items
  has_many :products, through: :cart_items, source: :product

  def add_product_to_cart(product)
    ci = cart_items.build
    ci.product = product
    ci.quantity = 1
    ci.save
  end
end

Step 3: 购物车设计 Part 2

1)显示购物车内物品数量
app/views/common/_navbar.html.erb