添加到购物车,但在Show#Cart

时间:2016-10-10 15:45:00

标签: ruby-on-rails

这是我的cart.rb型号

class Cart < ActiveRecord::Base
  has_many :tutors

  def current_cart
    if session[:cart_id]
      @current_cart ||= Cart.find(session[:cart_id])
    end
    if session[:cart_id].nil?
      @current_cart = Cart.create!
      session[:cart_id] = @current_cart.id
    end
    @current_cart
  end

  def add_tutor(tutor_id)
    tutor = Tutor.find(tutor_id)
    if tutor
      self.tutors << tutor
    end
    save
  end
end

这是carts_controller.rb

class CartsController < ApplicationController

  def show
    @cart = current_cart
  end

  def checkout
    @cart = current_cart
    name = params[:checkout][:your_name]
    email = params[:checkout][:your_email]
    message = params[:checkout][:your_hp]
    ApplicationMailer.checkout(@cart, name, email, message).deliver
    flash[:success] = "We have received your request and will be in touch with you shortly!"
    redirect_to root_path
  end

  def add_to_cart
    @cart = current_cart.add_tutor(params[:tutor_id])
    if @cart
      flash[:success] = "You have successfully added the tutor to your cart!"
      redirect_to tutors_path
    else
      flash[:danger] = "Oops! Something went wrong. Please try again!"
      redirect_to root_path
    end
  end

end

这里是添加到购物车功能的按钮

<%= button_to "Shortlist Tutor", add_to_cart_path(:tutor_id => tutor.id), :method => :post %>

添加到购物车功能似乎工作正常,因为它将我重定向到正确的页面,没有错误或类似的东西似乎出现。在我的rails控制台中,我可以在服务器中看到没有任何回滚。

Processing by CartsController#add_to_cart as HTML
  Parameters: {"authenticity_token"=>"da3XDg69FSCrEyn39v8Apty4aX40TJH85BeW49x/4R3MElKYxip1w7rpbWRBYj5hhZDAivf7Bxn4FK1dkHyKpg==", "tutor_id"=>"3"}
  Cart Load (0.2ms)  SELECT  "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1  [["id", 12]]
  Tutor Load (0.3ms)  SELECT  "tutors".* FROM "tutors" WHERE "tutors"."id" = ? LIMIT 1  [["id", 3]]
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction

这就是我在服务器中看到的内容。当我去购物车#show view时,我真的不太确定为什么我什么都看不到。

感谢我能得到的任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

检查你在params [:tutor_id]中收到的内容。

查看执行的SQL语句,在调用add_to_cart时,它看起来并没有保存。它只对推车和导师进行选择。