那麼一些雜誌或書籍從一位詩人打印5首詩的情況如何呢?
請記住,如果你有一位詩人,有很多詩歌和印刷有很多詩歌,以及你可以一直得到詩人。
Poet.poems.first.printings將返回詩人的第一首詩
的所有印刷或者你可以做Printing.poems.first.poet這樣你可以得到的第一個詩的詩人在印刷。
你將如何建立這些關係?具體來說,模型和數據庫表將是什麼樣子,以及如何使用它們來訪問關聯的數據?
我會因爲你使用,你需要一個連接表has_and_belogs_to_many協會設置了這樣
Poet :has_many poems
poem :belongs_to poet
poem :has_and_belongs_to_many printings
printing :has_many poems
,對詩歌和印刷
你將不得不遷移,看起來像這樣
CreatePoemsPrintingJoinTable < ActiveRecord::Migration
def self.up
create_table :poems_printings, :id => false do |t|
t.integer :poem_id
t.integer :printing_id
end
end
def self.down
drop_table :poems_printings
end
end
其他表很容易
CreateTablePoems < ActiveRecord::Migration
def self.up
create_table :poems, do |t|
t.integer :poet_id
end
end
def self.down
drop_table :poems
end
end
CreateTablePoets < ActiveRecord::Migration
def self.up
create_table :poets do |t|
end
end
def self.down
drop_table :poems
end
end
CreateTablePrintings < ActiveRecord::Migration
def self.up
create_table :printings do |t|
end
end
def self.down
drop_table :printings
end
end
如果一首詩可能出現在許多印刷品中,它會變得更加棘手,不確定這是否是這種情況? – house9
然後只是改變它,所以一首詩可以有很多印刷 – austinbv
這就是這種情況,我剛剛更新文本正如你們發佈的答案:X –