Rails使用来自不同ActiveRecord模型的列作为外键

时间:2018-11-15 11:10:50

标签: ruby-on-rails activerecord foreign-keys

class Model1
 #has an column "attr1"
end

class Model2
 #has an column "attr2"
end

class Model3
 #has an column "attr3"
 belongs_to :model2

 belongs_to my_model_1, class_name: 'Model1', primary_key: :attr1, foreign_key: "#{model2.attr2}-#{attr3}"
end

执行此操作时出现以下错误:

  `method_missing': undefined local variable or method `model2' for Model1 (call 'Model1.connection' to establish a connection):Class (NameError)

是否有一种方法像我要尝试的那样,将belongs_to关系中的列用作foreign_key的一部分?

1 个答案:

答案 0 :(得分:1)

您无法将动态值传递给:foreign_key,因此您将不得不使用为列名选择的值手动编写它:

belongs_to my_model_1, class_name: 'Model1', primary_key: :attr1,
                       foreign_key: "model2_attr2_attr3"

您可以签出文档here