views:

33

answers:

1

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.

+1  A: 

It looks to me that you misunderstood what has_many and belongs_to means. A user has many records and a record has many files. User does not belong_to a record, that makes no sense. So turn your relations around and i think you get what you want.

You would get:

(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
gregor