Как вставлять строки при использовании отношения "многие ко многим"
Автор вопроса: Daniel JompheОтветов: 3
Учитывая следующее, как я могу вставлять строки в свою базу данных? (Или что мне исправить в моей схеме?)
Модели:
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 для проверки.
Взгляните на этот пост " title = "как сохранить в базу данных с помощью ассоциаций в рельсах, защищающих массовое присвоение"> stackoverflow.com/questions/11665389/ juliangonzalez 27.07.2012
(изменить: название модели "Транзакция" может вызвать некоторые проблемы из-за ActiveRecord::Transactions. Есть билет на маяк.)
Ваша схема настроена неправильно. "references" - это псевдоним "belongs_to". Предмет и Транзакция не принадлежат транс_элементам, каждый из них имеет_много транс_элементов (в соответствии с вашими моделями)
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
Эта схема должна дать вам результаты, которые вы ищете:
create_table :items do |t|
t.string :name
end
create_table :purchase_items do |t|
t.belongs_to :item, :purchase, :null => false
t.integer :quantity
end
create_table :purchases do |t|
t.decimal :profit, :default => 0
end
Вот модели:
class Purchase < ActiveRecord::Base
has_many :purchase_items
has_many :items, :through => :purchase_items
end
class Item < ActiveRecord::Base
has_many :purchase_items
has_many :purchases, :through => :purchase_items
end
class PurchaseItem < ActiveRecord::Base
belongs_to :item
belongs_to :purchase
end