1

以這種情況爲例。關於Rails中正確關聯的問題

你有3種型號:

  1. 詩人 - 代表一首詩
  2. 詩的作者 - 代表由詩人
  3. 印寫的一首詩 - 表示包含任何形式的印刷出版物詩人的詩。

馬上蝙蝠詩人和詩是顯而易見的:

  • 詩人has_many
  • belongs_to詩人

與打印模型打交道時,它變得撲朔迷離我。

在這種情況下,印刷在某種意義上屬於詩人和詩人。你可以說一個詩人has_many打印或詩has_many打印這是有道理的,但相反的路線是棘手的...

那麼一些雜誌或書籍從一位詩人打印5詩的情況呢?或者,其中一首詩在10種不同的雜誌上發表?

它看起來好像印刷本身「屬於許多」詩歌或詩人。我知道這是錯的,但我只是想說清楚這一點。

所以,可回答的問題是這樣的: 你將如何建立這些關係?具體來說,模型和數據庫表將是什麼樣子,以及如何使用它們來訪問關聯的數據?

謝謝!

回答

2

那麼一些雜誌或書籍從一位詩人打印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 
+0

如果一首詩可能出現在許多印刷品中,它會變得更加棘手,不確定這是否是這種情況? – house9

+0

然後只是改變它,所以一首詩可以有很多印刷 – austinbv

+0

這就是這種情況,我剛剛更新文本正如你們發佈的答案:X –