NameError in StoreController#add_to_cart

本文修正了Rails应用程序中购物车添加商品过程的一个错误,并提供了正确的代码实现。主要修改包括去除model实例变量前的不必要符号及确保异常捕获时的语法正确性。
根据《web开发敏捷之道》第二版学习ror,第八章106页出现如上错误。
解决后代码:
def add_to_cart
begin
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error( "Attempt to access invalid product #{params[:id]}" )
flash[:notice] = "Invalid product"
redirect_to :action => :index
else
@cart = find_cart
@cart.add_product(product)
end
end

注意:1. product = Product.find(params[:id]) 前面没有@,书上有@是错误的。
2. rescue ActiveRecord::RecordNotFound 注意大小写。
Yes, your `functions.php` code is **mostly correct** and well-structured for implementing **selective checkout with checkboxes** in **WooCommerce**. However, there are a few **important considerations and improvements** to ensure everything works smoothly, especially with cart updates and session handling. --- ## ✅ Summary of What Your Code Does 1. **Adds checkboxes** to each cart item using `woocommerce_cart_item_name`. 2. **Handles AJAX requests** to update the cart based on selected items. 3. **Stores selected cart item keys** in session. 4. **Resets session data** after checkout. --- ## 🔍 Review and Suggestions ### ✅ 1. **Adding Checkboxes to Cart Items (Good)** ```php add_filter('woocommerce_cart_item_name', 'add_checkbox_to_cart_item', 10, 3); function add_checkbox_to_cart_item($item_name, $cart_item, $cart_item_key) { $checkbox = '<label><input type="checkbox" name="selected_items[]" value="' . esc_attr($cart_item_key) . '" checked> ' . $item_name . '</label>'; return $checkbox; } ``` - **✔️ Correct usage** of `woocommerce_cart_item_name` filter. - **✔️ Proper escaping** with `esc_attr()`. - You might want to **check if the item is selected** from session to persist state after AJAX updates. #### 🔧 Optional Enhancement: ```php $checked = WC()->session->__isset('selected_items') && in_array($cart_item_key, WC()->session->get('selected_items')) ? 'checked' : 'checked'; ``` --- ### ✅ 2. **AJAX Handler to Update Cart (Good)** ```php add_action('wp_ajax_update_selected_cart_items', 'handle_update_selected_cart_items'); add_action('wp_ajax_nopriv_update_selected_cart_items', 'handle_update_selected_cart_items'); function handle_update_selected_cart_items() { if (isset($_POST['selected_items']) && is_array($_POST['selected_items'])) { $selected_items = array_map('sanitize_text_field', $_POST['selected_items']); WC()->session->set('selected_items', $selected_items); foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { if (!in_array($cart_item_key, $selected_items)) { WC()->cart->set_quantity($cart_item_key, 0); } else { WC()->cart->set_quantity($cart_item_key, $cart_item['quantity']); } } wp_send_json_success(); } wp_send_json_error(); } ``` - **✔️ Correct AJAX handling** - **✔️ Proper sanitization** - **✔️ Session storage** - **⚠️ Potential issue**: Setting quantity to 0 might remove the item from the cart visually, but it's still in the cart object. This is acceptable for subtotal updates, but not ideal for checkout filtering. #### 🔧 Suggestion: Use a session variable to track selected items, but **don't modify cart quantities**, unless you want to reflect deselected items visually. Alternatively, **filter during checkout only**. --- ### ✅ 3. **Reset Session After Checkout (Good)** ```php add_action('woocommerce_thankyou', 'reset_selected_items_session'); function reset_selected_items_session($order_id) { WC()->session->__unset('selected_items'); } ``` - **✔️ Good cleanup** after checkout. - **Alternative**: You can also use `woocommerce_order_status_completed` for more control. --- ## ✅ Missing Part You are missing the **filter during checkout** that ensures only selected items are added to the order. ### 🔧 Add This: ```php add_filter('woocommerce_add_to_order_from_cart_item', 'filter_items_during_checkout', 10, 3); function filter_items_during_checkout($bool, $cart_item_key, $order) { $selected_items = WC()->session->get('selected_items', []); if (!in_array($cart_item_key, $selected_items)) { return false; // Skip this item } return $bool; } ``` This ensures that only selected items are included in the order. --- ## ✅ Final Checklist | Feature | Implemented | Notes | |------------------------------------|-------------|-------| | Add checkboxes to cart items | ✅ | Good | | AJAX handler for checkbox changes | ✅ | Working | | Store selected items in session | ✅ | Correct | | Filter items during checkout | ❌ (Missing) | Needed | | Reset session after checkout | ✅ | Good | --- ## ✅ Final Recommended `functions.php` Code ```php // Add checkbox to each cart item add_filter('woocommerce_cart_item_name', 'add_checkbox_to_cart_item', 10, 3); function add_checkbox_to_cart_item($item_name, $cart_item, $cart_item_key) { $checked = WC()->session->__isset('selected_items') && in_array($cart_item_key, WC()->session->get('selected_items')) ? 'checked' : 'checked'; $checkbox = '<label><input type="checkbox" name="selected_items[]" value="' . esc_attr($cart_item_key) . '" ' . $checked . '> ' . $item_name . '</label>'; return $checkbox; } // Handle AJAX request to update selected items add_action('wp_ajax_update_selected_cart_items', 'handle_update_selected_cart_items'); add_action('wp_ajax_nopriv_update_selected_cart_items', 'handle_update_selected_cart_items'); function handle_update_selected_cart_items() { if (isset($_POST['selected_items']) && is_array($_POST['selected_items'])) { $selected_items = array_map('sanitize_text_field', $_POST['selected_items']); WC()->session->set('selected_items', $selected_items); foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { if (!in_array($cart_item_key, $selected_items)) { WC()->cart->set_quantity($cart_item_key, 0); } else { WC()->cart->set_quantity($cart_item_key, $cart_item['quantity']); } } wp_send_json_success(); } wp_send_json_error(); } // Only include selected items in order add_filter('woocommerce_add_to_order_from_cart_item', 'filter_items_during_checkout', 10, 3); function filter_items_during_checkout($bool, $cart_item_key, $order) { $selected_items = WC()->session->get('selected_items', []); if (!in_array($cart_item_key, $selected_items)) { return false; } return $bool; } // Reset session after checkout add_action('woocommerce_thankyou', 'reset_selected_items_session'); function reset_selected_items_session($order_id) { WC()->session->__unset('selected_items'); } ``` --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值