【发布时间】:2016-07-22 10:17:03
【问题描述】:
我正在尝试在 OrdersController#new 操作中调用一些 ActiveRecord 方法。 我已经在 Rails Console 中测试了代码,它按我的预期工作。 但是在控制器动作中它不会产生相同的
order has_many cart_items
cart has_many cart_items
cart_items belong_to order cart_items
belong_to cart
cart_items belong_to product
product has_many cart_items
def new
@order.new
@order.cart_items = current_cart.cart_items
@order.save
current_cart.cart_items.destroy_all
end
现在 current_cart 是一个 application_controller 方法,用于检查当前用户是否有购物车。如果是,它会从数据库中拉出该购物车,如果用户没有,那么它会为用户创建一个新的购物车。我在这里要做的是当用户完成他们的订单时,我试图将 cart_items 从 current_cart 转移到订单,然后清除购物车。
当我在 Rails 控制台中执行此操作时,它给了我想要的东西。使用 current_cart 中的 cart_items 订购,在我在购物车上运行 destroy_all 后,我有一个空的活动记录关联数组。
当我在我的控制器中测试这个时,Order 和 Cart 返回一个空的活动关联数组。
这是怎么回事?
#application controller method of finding current_users cart
def current_cart
# if user is logged in
if current_user
@user = current_user
# checking user to see if account is confirmed and verified
if @user.confirmed_at != nil
# checking if user already has cart in cart database
if Cart.find_by(users_id: @user.id) != nil
# find a row in the database where users_id: equal to @user.id
# where clause does not work here
cart = Cart.find_by(users_id: @user.id)
session[:cart_id] = cart.id
cart.save
#establish Cart session cart for user
Cart.find(session[:cart_id])
else
# create a new Cart Object for user.assign current_user's id to cart object
cart = Cart.new
cart.users_id = @user.id
# save it to get cart id assign session[:cart_id] == cart.id
cart.save
session[:cart_id] = cart.id
end
end
end
end
class CartItemsController < ApplicationController
before_action :set_cart_item, only: [:show, :edit, :update, :destroy]
# scope for most_recent and subtotal
# find out if rails sorts on update column cuz this is annoying.
def create
# grabbing cart from application controller current_cart method
@cart = current_cart
# session[:cart_id] = @cart.id
# individual product items get added to cart item and added to cart and saved
@cart_item = @cart.cart_items.build(cart_item_params)
@cart.save
end
def update
@cart = current_cart
# finding cart_items by cart_id
@cart_item = @cart.cart_items.find(params[:id])
# @cart_items.order(:id)
@cart_item.update_attributes(cart_item_params)
@cart_items = @cart.cart_items.order(:id)
# redirect 'cart_show_path'
@cart.save
end
def destroy
@cart = current_cart
@cart_item = @cart.cart_items.find(params[:id])
@cart_item.destroy
@cart_items = @cart.cart_items
@cart.save
end
private
def set_cart_item
@cart_item = CartItem.find(params[:id])
end
def cart_item_params
params.require(:cart_item).permit(:cart_id, :product_id, :unit_price, :quantity, :total_price)
end
end
【问题讨论】:
标签: ruby-on-rails activerecord