0

如何设置以下关联:

class Midatum < ActiveRecord::Base
 # ..., diagn1, diagn2, diagn3
 # sample data:
 #  ..., "0123", nil   ,"0124"
 #  ..., "0123", nil   ,"0124"
 #  ..., "0123", "1123", nil  
 belongs_to :icd9, :foreing_key => :diagn1
 belongs_to :icd9, :foreing_key => :diagn2
 belongs_to :icd9, :foreing_key => :diagn3
end

class icd9 < ActiveRecord::Base
 # icd9, description 
 # sample data:(unique)
 #"0123", "some text"
 #"0124", "some other text"
 #"1123", "description text"
 #"1133", "description text"
 has_many :midata, :foreing_key => :icd9, :primary_key => :icd9
end

这不起作用。这对某人来说可能很明显,但对我来说不是。该数据库是一个遗留数据库并且是只读的。我需要建立这个关联才能处理数据。

4

1 回答 1

0

这个答案来自 Rails 专家,它确实解决了我的问题。我发布它以防其他人有同样的问题。

belongs_to :icd9_a, :foreign_key => :diagn1, :class_name => "Icd9"
belongs_to :icd9_b, :foreign_key => :diagn2, :class_name => "Icd9"
belongs_to :icd9_c, :foreign_key => :diagn3, :class_name => "Icd9"

但这意味着您需要使用所有三种方法查询关联: m = Midatum.first m.icd9_a m.icd9_b m.icd9_c

同样,在 Icd9 类中,您将需要三个具有唯一名称的独立关联:

class Icd9 < ActiveRecord::Base
 self.primary_key = :icd9

 has_many :midata_a, :foreign_key => :diagn1, :class_name => "Midatum"
 has_many :midata_b, :foreign_key => :diagn2, :class_name => "Midatum"
 has_many :midata_c, :foreign_key => :diagn3, :class_name => "Midatum"

end

另请注意,由于 icd9 表没有“id”列,而是使用“icd9”列作为主键,因此您需要像我一样设置它:

 self.primary_key = :icd9
于 2013-09-10T17:51:45.770 回答