Skip to main content

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

Rails • Asked by Robson Montenegro

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"

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

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

foo => 1, :custom_id => 100)
bar =>foo)

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

The code is here:

You have to define the foreign key to on the belongs_to side.

Class Foo
  has_many :bars

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

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

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.