鑑於以下情況,我如何在我的數據庫中插入行? (或者我應該在我的架構是否正確?)如何在使用多對多關係時插入行
型號:
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
我失去了幾個小時試圖插入記錄,使用軌道控制檯來測試的東西出。
看看這個帖子http://stackoverflow.com/questions/11665389/how-to-save-to-database-with-associations- 11681454#11681454 – juliangonzalez 2012-07-27 05:11:55