如何设置以下关联:
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
这不起作用。这对某些人来说可能是显而易见的,但不适合我。数据库 是一个遗留数据库和readonly。我需要建立这个关联才能使用数据。
答案 0 :(得分: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