gpt4 book ai didi

ruby-on-rails - 在 ruby​​ on rails 中将用户 ID 作为外键存储到另一个表中的基本规则

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:23 25 4
gpt4 key购买 nike

作为初学者,我认为将当前用户 session ID 存储到另一个表中会很容易,因为我设法将用户 ID 放入 Line_Items 表中,但是我相信我还没有理解将一个主键存储到另一个表中的基本原理另一个表作为外键,在我的例子中,它试图将 session User_ID 存储到 Carts 表中,因为购物车属于用户并且用户有很多购物车。非常感谢有关此问题的任何代码或任何有用的链接。以下是我的模型。如果需要任何其他代码以获得帮助,请告诉我。谢谢:

class User < ActiveRecord::Base
attr_accessible :email, :first_name, :last_name, :password, :role, :subscriber, :name


has_many :line_item
has_many :cart


class NotAuthorized < StandardError; end
end

购物车.rb:

class Cart < ActiveRecord::Base
attr_accessible :user_id

has_many :line_items, dependent: :destroy
belongs_to :user

def add_phone(phone, current_user = 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

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

# returns the total number of items in a cart
def number_of_items
total = 0
line_items.each do |item|
total += item.quantity
end
total
end

def empty?
number_of_items == 0
end

def grand_total
grand_total = 0
line_items.each do |item|
grand_total += item.quantity * item.phone.price
end
grand_total
end

end

最佳答案

你的关系声明有误。他们应该是复数,试试看是否有帮助,你的购物车和订单项模型上也应该有一个 user_id。

has_many :line_items
has_many :carts

关于ruby-on-rails - 在 ruby​​ on rails 中将用户 ID 作为外键存储到另一个表中的基本规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21740377/

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