Database nesting layout confusion
        Posted  
        
            by arzon
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by arzon
        
        
        
        Published on 2010-04-21T11:58:18Z
        Indexed on 
            2010/04/21
            12:03 UTC
        
        
        Read the original article
        Hit count: 353
        
I'm no expert in databases and a beginner in Rails, so here goes something which kinda confuses me...
Assuming I have three classes as a sample (note that no effort has been made to address any possible Rails reserved words issue in the sample).
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
Upon entering records, the database contents will appear as such. My issue is that if there are a lot of Files for the same Record, there will be duplicate record names. This will also be true if there will be multiple Records for the same user in the the Users table.
I was wondering if there is a better way than this so as to have one or more files point to a single Record entry and one or more Records will point to a single User. BTW, the File names are unique.
Files table:
id   name    
1   name1       
2   name2    
3   name3  
4   name4  
Records table:
id   file_id record_name  record_type
1   1       ForDaisy1    ...    
2   2       ForDonald1   ...
3   3       ForDonald2   ...
4   4       ForDaisy1    ...    
Users table:
id  record_id  username  
1   1           Daisy    
2   2           Donald    
3   3           Donald
4   4           Daisy
Is there any way to optimize the database to prevent duplication of entries, or this should really the correct and proper behavior. I spread out the database into different tables to be able to easily add new columns in the future.
© Stack Overflow or respective owner