gpt4 book ai didi

ruby-on-rails - 使用多对多关系时如何插入行

转载 作者:行者123 更新时间:2023-12-04 06:17:48 25 4
gpt4 key购买 nike

鉴于以下内容,我如何在我的数据库中插入行? (或者我应该在我的模式中更正什么?)

楷模:

class Item < ActiveRecord::Base
has_many :tran_items
has_many :transactions, :through => :tran_items
end
class TranItem < ActiveRecord::Base
belongs_to :item
belongs_to :transaction
end
class Transaction < ActiveRecord::Base #answer: rename Transaction
has_many :tran_items
has_many :items, :through => :tran_items
end

架构:
create_table :items do |t|
t.references :tran_items #answer: remove this line
t.string :name
end
create_table :tran_items do |t|
t.belongs_to :items, :transactions, :null => false #answer: unpluralize
t.integer :quantity
end
create_table :transactions do |t|
t.references :tran_items #answer: remove this line
t.decimal :profit
end

我花了几个小时试图插入记录,使用 rails 控制台来测试。

最佳答案

(编辑:由于 ActiveRecord::Transactions,模型名称“Transaction”可能会给您带来一些问题。There is a lighthouse ticket。)

您的架构设置不正确。 “references”是“belongs_to”的别名。项目和交易不属于 trans_items,他们每个 has_many trans_items(根据您的型号)

create_table :items do |t|
t.string :name
end
create_table :tran_items do |t|
t.belongs_to :item, :transaction, :null => false
t.integer :quantity
end
create_table :transactions do |t|
t.decimal :profit, :default => 0
end

(编辑:使belongs_to 单数)

您是否删除了数据库并重新运行迁移以构建新模式?

rake db:drop && rake db:create && rake db:migrate

这是我在控制台中得到的:
>> i = Item.create(:name => 'My Item')    
=> #<Item id: 2, name: "My Item">
>> t = Transaction.create(:profit => 100)
=> #<Transaction id: 2, profit: #<BigDecimal:2411d2c,'0.1E3',4(8)>>
>> t.tran_items.create(:item => i)
=> #<TranItem id: nil, item_id: 2, transaction_id: 2, quantity: nil>

关于ruby-on-rails - 使用多对多关系时如何插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/285456/

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