gpt4 book ai didi

ruby - Sequel如何保存新建的关联模型?

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

假设我有这样的东西:

# Schema:
DB.create_table :transactions do
primary_key :id
foreign_key :card_id, :cards
Integer :amount
end
DB.create_table :cards do
primary_key :id
foreign_key :transaction_id, :transactions
Intger :number
end

# Models:
class Transaction < Sequel::Model
one_to_one :card
end
class Card < Sequel::Model
one_to_one :transaction
end

我如何使它工作,以便它保存 transcard 以及它们各自的关联?

trans = Transaction.new(:amount => 100)
card = Card.new(:number => 4000500060007000)
trans.card = card
trans.save

就目前而言,这是行不通的,因为 card 没有首先保存,Sequel 会抛出“无主键”错误。如果我先保存card,它不会得到transaction的id。

基本上,我正在努力避免这种情况:

# Save without associations first, but this will assign primary keys
trans.save
card.save

# Now, manually create associations
trans.card = card
card.trans = trans

# Re-save again, this time with associations
trans.save
card.save

最佳答案

您可能想尝试将关联类型更改为更类似的内容:

# Schema:
DB.create_table :transactions do
primary_key :id
Integer :amount
end
DB.create_table :cards do
primary_key :id
foreign_key :transaction_id, :transactions
Integer :number
end

# Models:
class Transaction < Sequel::Model
one_to_many :card
end
class Card < Sequel::Model
one_to_one :transaction
end

现在你创建为:

trans = Transaction.new(:amount => 100)
trans.save
trans.add_card(:number => 4000500060007000)

这将允许所有相同的选项,并允许(但当然不要求)将交易拆分到多张卡上。

关于ruby - Sequel如何保存新建的关联模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16457027/

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