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的一部分?
答案 0 :(得分:1)
您无法将动态值传递给:foreign_key
,因此您将不得不使用为列名选择的值手动编写它:
belongs_to my_model_1, class_name: 'Model1', primary_key: :attr1,
foreign_key: "model2_attr2_attr3"
您可以签出文档here。