【问题标题】:How to use :cart_id to find the current cart by session?如何使用 :cart_id 按会话查找当前购物车?
【发布时间】:2013-05-28 07:32:07
【问题描述】:

当我阅读《Agile web development with rails, Task D》一书时,我完全糊涂了。

我知道基类中的 current_cart 方法可以通过会话找到目标购物车。但是,我不知道 sysbol :card_id 来自哪里。

lineItemController调用current_cart方法时,:cart_id的值是多少?

更重要的是,我已经运行了常见的“rails generate scaffold line_item product_id:integer cart_id integer”。这两种cart_id是什么关系?

class ApplicationController < ActionController::Base
  protect_from_forgery

  private
    def current_cart
       Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
       cart = Cart.create
       session[:cart_id] = cart.id
       cart
    end
end

【问题讨论】:

  • :card_id 只是一个键;一个符号。类似于字符串。这只是稍后在您的会话哈希中识别您的cart.id 的一种方式。

标签: ruby-on-rails ruby


【解决方案1】:

session[:cart_id] 的初始值为 nil,因此Cart.find(session[:cart_id]) 将抛出错误,因此救援块的代码将被执行。它做了三件事

1. Create a new Cart
2. Save the id of newly created Cart in session
3. return the newly created cart

当调用相同的方法时,它只会返回Cart.find(session[:cart_id])

【讨论】:

    【解决方案2】:

    购物车有很多 line_item。购物车和 line_items 之间存在一对多的关系。 所以购物车的 id 将是 line_items 中的外键,即 cart_id。

    :cart_id 包含 cart_id 的值。

    因此,在方法 current_cart 中,您试图找到 id 等于 cart_id 的购物车。

    如果 id = cart_id 的卡不存在,则会抛出错误,并在救援块中创建新的购物车并将其 id 保存到 session[:cart_id] 并返回购物车。

    【讨论】:

      猜你喜欢
      • 2015-02-04
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 2014-09-14
      • 1970-01-01
      • 2011-08-18
      相关资源
      最近更新 更多