Как вставить строки при использовании отношения «многие ко многим» - PullRequest
4 голосов
/ 13 ноября 2008

Учитывая следующее, как я могу вставить строки в мою базу данных? (Или что я должен исправить в моей схеме?)

Модель:

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 для проверки.

Ответы [ 3 ]

6 голосов
/ 13 ноября 2008

(редактировать: название модели «Транзакция» может вызвать некоторые проблемы из-за ActiveRecord :: Transactions. Есть билет на маяк .)

Ваша схема настроена неправильно. «Ссылки» - это псевдоним «принадлежат». Предмет и транзакция не принадлежат 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

(редактировать: сделать принадлежащим - в единственном числе)

Вы сбросили базу данных и повторно запустили миграции, чтобы построить новую схему?

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>
1 голос
/ 13 ноября 2008

Эта схема должна дать вам результаты, которые вы ищете:

   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

Теперь с помощью консоли:

>> i = Item.create(:name => 'Item One')
=> #<Item id: 1, name: "Item One">
>> p = Purchase.create(:profit => 100)
=> #<Purchase id: 1, profit: #<BigDecimal:2458cf4,'0.1E3',4(8)>>
>> p.purchase_items.create(:item => i)
=> #<PurchaseItem id: 1, item_id: 1, purchase_id: 1, quantity: nil>
1 голос
/ 13 ноября 2008

Если я правильно понял.

item = Item.new(:name => "item")
item.transactions.build(:name => "transaction")
item.save!
...