0
votes

I'm using Rails with a legacy postgres database, meaning no migrations. The schema is defined separately.

I have two tables: notification and notification_type. The notification_type table has an ID (primary key) and a code column. The notification table has a notitification_type column with a foreign key on the notificiation_type table's code column.

class Notification < ActiveRecord::Base
  ...
  belongs_to :notification_type, foreign_key: 'notification_type'
  ...

NotificationType:

class NotificationType < ActiveRecord::Base
  has_many :notifications
end

When I call create on the notification model, it gives me a foreign key error because it's trying to create with the ID column of notification_type, not the code column.

ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "notification" violates foreign key constraint "notification_notification_type_fkey" DETAIL: Key (notification_type)=(18) is not present in table "notification_type".

Where 18 is the ID, but I need it to use the code, which would be something like 1 or 2. I saw the association_foreign_key value, but it seems that it only works with the has_and_belongs_to_many association.

psql, just for closure:

Foreign-key constraints: "notification_notification_type_fkey" FOREIGN KEY (notification_type) REFERENCES notification_type(code)

Basically, how do I get rails to honor the foreign key relationships in my database instead of always using the primary key?

1

1 Answers

3
votes

Just do:

belongs_to :notification_type, foreign_key: 'notification_type', primary_key: 'code'

The primary_key defaults to id but you can use anything you want.

You'll want to specify the same options for your has_many :notifications association - the has_many is completely unaware of it's associated belongs_to, so it needs to know if you're using non-standard keys as well.