简体   繁体   中英

Rails use column from different activerecord model as foreign key

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

I get the following error doing this:

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

Is there a way of using a column from belongs_to relation as part of the foreign_key the way I'm trying to do?

You can't pass a dynamic value to :foreign_key so you will have to write it manually using the value you've chosen for the column name:

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

You can check out the docs here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM