makandra/active_type

Unexpected foreign_key guess with has_many

Closed this issue · 2 comments

While using an ActiveType Model I noticed that a has_many association didn't guess the correct foreign key.

Here is a minimal example:

class Competence
  belongs_to :box
  ...
end

class Box < ApplicationRecord
  ...
end

class Box::AsForm < ActiveType::Record[Box]
  has_many :competences
  ...
end

The following command did not succeed:

Box::AsForm.last.competences.last
  Box::AsForm Load (0.1ms)  SELECT  "boxes".* FROM "boxes" ORDER BY "boxes"."id" DESC LIMIT ?  [["LIMIT", 1]]
  Competence Load (0.2ms)  SELECT  "competences".* FROM "competences" WHERE "competences"."as_form_id" = ? ORDER BY "competences"."id" DESC LIMIT ?  [["as_form_id", 1], ["LIMIT", 1]]
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: competences.as_form_id: SELECT  "competences".* FROM "competences" WHERE "competences"."as_form_id" = ? ORDER BY "competences"."id" DESC LIMIT ?

I expected Box::AsForm to link to competences via box_id, however AR wanted to use as_form_id as foreign key. Explicitly setting foreign_key fixed the problem.

active_type version: 0.6.5
rails version: 5.0.1

I agree this would be the desired behavior. I've taken a look how AR determines the foreign key, and it's unfortunately done in a way that we cannot easily override.
Maybe the fix would be to override has_many / has_one for ActiveType::Record and automatically add the foreign_key: option.

Released in 1.1.0.