Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert rows when using a many-to-many relation

Given the following, how could I insert rows in my db? (Or what should I correct in my schema?)

Models:

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

Schema:

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

I lost a few hours trying to insert records, using the rails console to test things out.

like image 350
Daniel Jomphe Avatar asked Nov 12 '08 21:11

Daniel Jomphe


People also ask

How do I insert the same data in multiple rows?

MySQL INSERT multiple rows statement In this syntax: First, specify the name of table that you want to insert after the INSERT INTO keywords. Second, specify a comma-separated column list inside parentheses after the table name. Third, specify a comma-separated list of row data in the VALUES clause.

How do you manage many-to-many relationships in SQL?

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa. To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.


1 Answers

(edit: the model name "Transaction" may cause you some problems due to ActiveRecord::Transactions. There is a lighthouse ticket.)

Your schema is not set up correctly. "references" is an alias to "belongs_to". Item and Transaction don't belong_to trans_items, they each has_many trans_items (according to your models)

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

(edit: make belongs_to singular)

Did you drop the db and re-run the migrations to build the new schema?

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

Here is what I get in the console:

>> 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>
like image 136
Mike Breen Avatar answered Oct 24 '22 15:10

Mike Breen