从购物车建立订单

时间:2015-10-23 14:14:38

标签: ruby-on-rails ruby ruby-on-rails-4

我一直在尝试构建Cart + Cart / OrderItem + Order组合简单而有效的问题。我在网上环顾四周但是找不到合适的东西,所以我尝试了一些但是......我有点被封锁了,我不知道如何继续这个。问题是我不知道如何获得订单中的物品并从头开始购物车(顺便说一下它有点乱)。此外,一个很好的简单教程也将受到赞赏。请注意我已经通过敏捷网络的书籍示例,但由于某种原因我没有遵循它,它似乎不是我想要的。

控制器 - 购物车+订单

class CartsController < ApplicationController   before_filter :initialize_cart

  def add
    @cart.add_item params[:id]
    session["cart"] = @cart.serialize
    product = Product.find(params[:id])
    redirect_to :back, notice: "Added #{product.name} to cart."   end

  def show   end

  def checkout
    @order = Order.new user: User.new   end end

class OrdersController < ApplicationController
    def index
    @orders = Order.order('created_at desc').page(params[:page])
  end

  def show
  end

  def new
    @order = Order.new
  end

  def create
    @order = Order.new(order_params)
    respond_to do |format|
      if @order.save
        format.html { redirect_to root_path, notice: 
          'Thank you for your order' }
        format.json { render action: 'show', status: :created,
          location: @order }
      else
        format.html { render action: 'new' }
        format.json { render json: @order.errors,
          status: :unprocessable_entity }
      end
    end
  end

  private
    def set_order
      @order = Order.find(params[:id])
    end

    def order_params
      params.require(:order).permit(:pay_type, :user_id)
    end
end

现在的模型

class Order < ActiveRecord::Base
  belongs_to :user
  PAYMENT_TYPES = [ "Check", "Credit card", "Purchase order" ]
  validates :pay_type, inclusion: PAYMENT_TYPES
end

class CartItem
  attr_reader :product_id, :quantity

  def initialize product_id, quantity = 1
    @product_id = product_id
    @quantity = quantity
  end

  def product
    Product.find product_id
  end

  def total_price
    product.price * quantity
  end
end

class Cart
  attr_reader :items

  def self.build_from_hash hash
    items = if hash["cart"] then
      hash["cart"]["items"].map do |item_data|
        CartItem.new item_data["product_id"], item_data["quantity"]
      end
    else
      []
    end

    new items
  end

  def initialize items = []
    @items = items
  end

  def add_item product_id
    item = @items.find { |item| item.product_id == product_id }
    if item
      item+=1
    else
      @items << CartItem.new(product_id)
    end
  end

  def empty?
    @items.empty?
  end

  def count
    @items.length
  end

  def serialize
    items = @items.map do |item|
      {
        "product_id" => item.product_id,
        "quantity" => item.quantity
      }
    end

    {
      "items" => items
    }
  end

  def total_price
    @items.inject(0) { |sum, item| sum + item.total_price }
  end
end

谢谢。

0 个答案:

没有答案