数据库嵌套模型布局混乱

时间:2010-04-21 11:58:18

标签: ruby-on-rails ruby activerecord

我不是数据库方面的专家,也不是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 个答案:

答案 0 :(得分: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