Stuck in a - at first sight - simple problem in RoR. I am sure that is easy, but none answer here in SO helped me too much.
I have two ActiveRecord models: Foo has many Bars:
class Foo < ApplicationRecord
has_many :bars
end
class Bar < ApplicationRecord
belongs_to :foo
end
That works like a charm. But I would like to use another field of Foo as foreign_key. The default is foo_id I would like to use custom_id as my foreign key. So I tried this (as many solutions over the web suggested):
class Foo < ApplicationRecord
has_many :bars, :foreign_key => 'custom_id', :class_name => 'Bars'
end
class Bars < ApplicationRecord
belongs_to :foo, :class_name => 'Foo'
end
But that doesn't work. i.e. ActiveRecord keeps binding Foo to Bars using foo_id.
Note: Including a self.primary_key='custom_id' in Foo would partially work. but I don't think that is a good idea. I want to keep foo_id as the primary key
UPDATE:
Given the feedback -Thank you guys-, I uploaded that example here https://github.com/montenegrodr/temporary_repository_ror :
UPDATE #2:
The answers does not satisfy the question above. Why the test is failing, my assumption is that it shouldn't fail.
UPDATE #3:
There're a couple of new answers I still need to assess. Will do that within 24 hours. Thanks.
UPDATE #4:
Thank you guys for all the answers. But none of them satisfied the criteria. I need to have that test passing. If it is not possible, can someone explain why? Is it a rails constraint?