gpt4 book ai didi

ruby-on-rails - 创建订单项记录时将 session 用户 ID 添加到 Line_Items 表中 - Ruby on Rails

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:26 25 4
gpt4 key购买 nike

我正在尝试将用户 session ID 添加到 Line_Items 表中。我到处研究但找不到答案,这就是为什么不得不在这里发布它的原因。此应用程序成功地将电话 ID 和购物车 ID 添加到 Line_Items 表中,但在我尝试电话和购物车 ID 的类似方法时不允许我添加用户 session ID。有关我当前的实现,请参见下文:

Line_Items Controller :

def create
# current_cart method in application_controller.rb
@cart = current_cart
phone = Phone.find(params[:phone_id])
if phone.stock > 0
@line_item = @cart.add_phone(phone.id )
if @line_item.save
redirect_to :back, notice: " '#{phone.model}' has been added to your cart."
else
render action: "new"
end
else
redirect_to :back, notice: " Cannot add: '#{phone.model}' - stock level is too low."
end
end

Cart.rb 模型:

def add_phone(phone_id)
current_item = line_items.find_by_phone_id(phone_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(phone_id: phone_id)
current_item.quantity = 1
end
current_item.phone.stock -= 1
current_item.phone.save
current_item
end

# returns true if stock level is greater than zero
def can_add(phone)
phone.stock > 0
end

如果需要更多代码,请告诉我。

最佳答案

问题是 Rails 中的模型类对 Controller 和 session 一无所知。我假设您正在使用某种身份验证机制,在您的 session 中为您提供 current_user ...因此我们必须将其添加到您的 add_phone 方法中。

在 Controller 中,我将更改这一行:


@line_item = @cart.add_phone(phone.id)

为此:


@line_item = @cart.add_phone(phone, current_user)

(请注意这里有两个变化 - 一个是传递电话而不是它的 ID,因为你已经找到了它,另一个是传递当前用户。

然后我们要将您的 add_phone 方法更改为如下所示:

def add_phone(phone, current_user = nil)
# make sure your Item class initializes quantity to o, not nil.
current_item = line_items.find_or_initialize_by_phone_id(phone.id)

current_item.increment!(:quantity)
current_item.phone.decrement!(:stock)
current_item.user = current_user
current_item.phone.save
current_item
end

请注意,我默认将用户设置为 nil ... 这样,您已有的不提供该字段的代码将继续工作。我还使用 find_or_initialize_by 帮助程序稍微简化了您的方法...避免了“if”测试。此外,递增和递减助手稍微清理了代码的意图。

您应该确保您的订单项类别包括


属于:用户

如果您发现自己处于需要了解 current_user 以获得大量域逻辑的情况,您可能需要查看 sentient_user gem。

关于ruby-on-rails - 创建订单项记录时将 session 用户 ID 添加到 Line_Items 表中 - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21650277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com