如何使用Sequel保存新创建的关联模型?

时间:2013-05-09 07:52:10

标签: ruby sequel

假设我有这样的事情:

# 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

1 个答案:

答案 0 :(得分:3)

您可能想尝试将关联类型更改为更像:

# 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)

这将允许所有相同的选项以及允许(但肯定不要求)交易分成多张卡。