CodexBloom - Programming Q&A Platform

Rails 7.1: best practices for ActiveRecord composite primary key implementing PostgreSQL?

👀 Views: 271 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
ruby rails postgresql Ruby

I tried several approaches but none seem to work... I'm migrating some code and I've searched everywhere and can't find a clear answer..... I'm currently working on a Rails 7.1 application using PostgreSQL, and I'm working with scenarios with ActiveRecord when trying to implement composite primary keys. I'm using the `composite_primary_keys` gem to manage this, but I'm running into issues when trying to create new records. For instance, I'm trying to define a model like this: ```ruby class Order < ApplicationRecord self.primary_keys = :user_id, :order_id # Associations and validations here end ``` But when I try to create a new order, I get the following behavior: ``` ActiveRecord::RecordInvalid: Validation failed: User must exist ``` I have the following code to create an order: ```ruby Order.create(user_id: 1, order_id: 123, other_attributes: 'value') ``` I've ensured that the `User` model is correctly associated with the `Order` model. The scenario arises only when I try to create a record without the `user_id` being a valid primary key in the `users` table. I've also checked that the foreign key constraints are correctly set in the database schema: ```ruby create_table :orders, id: false do |t| t.integer :user_id, null: false t.integer :order_id, null: false t.timestamps end add_foreign_key :orders, :users, column: :user_id ``` I've tried running database migrations and ensuring that the gem is up to date, but the scenario continues. Is there something I'm missing in either the model setup or the way I'm trying to create records? Any insights would be appreciated! My development environment is Ubuntu. Any help would be greatly appreciated! I'm using Ruby 3.9 in this project. I'm using Ruby 3.11 in this project. What would be the recommended way to handle this?