All threads / How to force a has_many association using a different column as foreign key

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to force a has_many association using a different column as foreign key

Robson Montenegro asked in Rails

Stuck in a - at first sight - simple problem in RoR. I have two ActiveRecord models: Foo has many Bars.. But I want to bind them by "custom_id" (not the default id):

class Foo < ApplicationRecord
  has_many :bars, :class_name => "Bar", :foreign_key => "custom_id"
end

class Foo < ApplicationRecord
  has_many :bars, :class_name => "Bar", :foreign_key => "custom_id"
end

Given that, I'd guess this pass would PASS, but it doesnt:

foo = Foo.new(:id=> 1, :custom_id => 100)
bar = Bar.new(:foo=>foo)

assert bar.custom_id == foo.custom_id # bar.custom_id == 1 and foo.custom_id == 100

The code is here: https://github.com/montenegrodr/temporary_repository_ror

You have to define the foreign key to on the belongs_to side. https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to

Class Foo
  has_many :bars
end

class Bar
  belongs_to :custom, class_name: 'Foo', foreign_key: "custom_id", primary_key: 'custom'
end

In this case Foo has to have a custom as primary key.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 38,558+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.