2010-04-21 36 views
1

我在數據庫方面的專家和Rails的初學者,所以這裏去一些東西,有點讓我困惑...數據庫模型嵌套佈局混亂

假設我有三個類爲樣本(注意,沒有力氣了是爲了解決樣例中任何可能的Rails保留字問題)。

class File < ActiveRecord::Base 
    has_many :records, :dependent => :destroy 
    accepts_nested_attributes_for :records, :allow_destroy => true 
end 

class Record < ActiveRecord::Base 
    belongs_to :file 
    has_many :users, :dependent => :destroy 
    accepts_nested_attributes_for :users, :allow_destroy => true 
end 

class User < ActiveRecord::Base 
    belongs_to :record 
end 

一旦輸入記錄,數據庫內容將如此顯示。我的問題是,如果同一記錄中有很多文件,則會有重複的記錄名稱。如果Users表中的同一用戶有多個記錄,則這也是正確的。

我想知道是否有比這更好的方法,以便有一個或多個文件指向單個記錄條目,並且一個或多個記錄將指向單個用戶。順便說一下,文件名是唯一的。

文件表:

id name  
1 name1  
2 name2  
3 name3 
4 name4 

記錄表:

id file_id record_name record_type 
1 1  ForDaisy1 ...  
2 2  ForDonald1 ... 
3 3  ForDonald2 ... 
4 4  ForDaisy1 ...  

用戶表:

id record_id username 
1 1   Daisy  
2 2   Donald  
3 3   Donald 
4 4   Daisy 

有什麼辦法來優化數據庫,以防止項目重複,或本應該真正的正確和正確的行爲。我將數據庫分散到不同的表中,以便將來能夠輕鬆添加新列。

回答

1

在我看來,你誤解了has_many和belongs_to的意思。用戶有很多記錄,記錄有很多文件。用戶不屬於記錄,這是沒有意義的。所以把你的關係轉到我想你得到你想要的東西。

你會得到:

(File, id, record_id, name) 
(Record, id, user_id, name, ...) 
(User, name, ...) 

class File < ActiveRecord::Base 
    belongs_to :record 
end 

class Record < ActiveRecord::Base 
    belongs_to :user 
    has_many :files 
end 

class User < ActiveRecord::Base 
    has_many :records 
    has_many :files, :through => :records 
end