StarMan
StarMan

Reputation: 29

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?

Upvotes: 1

Views: 46

Answers (1)

Ju Liu
Ju Liu

Reputation: 3999

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.

Upvotes: 1

Related Questions