Home > OS >  Rails 6.0 has_many - belongs_to failing to identify the foreign key
Rails 6.0 has_many - belongs_to failing to identify the foreign key

Time:08-05

I have the 2 models Loan::Transaction and Loan::Transaction::Transition. They are both inside the folder "models" and inside "loan". The second is also inside the folder "transaction".

1 Loan::Transaction has many Loan::Transaction::Transition
1 Loan::Transaction::Transition belongs to 1 Loan::Transaction

Loan::Transaction::Transition has the column loan_transaction_id

migration:

class CreateLoanTransactionTransitions < ActiveRecord::Migration[6.0]
  def up
    create_table :loan_transaction_transitions, id: :uuid do |t|
      t.timestamps
      t.references :loan_transaction, type: :uuid, null: false, index: true,
                                      foreign_key: { to_table: :loan_transactions }
      t.string :reason
      t.references :made_by, type: :uuid, null: true, foreign_key: { to_table: :users }
    end
    add_column :loan_transaction_transitions, :from_status, :transaction_status, null: false
    add_column :loan_transaction_transitions, :to_status,   :transaction_status, null: false
  end

  def down
    drop_table :loan_transaction_transitions
  end
end

Transition class:

class Loan::Transaction::Transition < ApplicationRecord
  validates :to_status, presence: true
  validates :from_status, presence: true
  validates :loan_transaction_id, presence: true

  belongs_to :made_by, class_name: 'User', foreign_key: 'made_by_id', optional: true
  belongs_to :loan_transaction, class_name: 'Loan::Transaction', foreign_key: 'loan_transaction_id', inverse_of: :transitions
end

Transaction class:

class Loan::Transaction < ApplicationRecord
  extend ActiveSupport::Concern
  
  has_many :transitions, class_name: 'Transaction::Transition', dependent: :destroy, foreign_key: 'loan_transaction_id', inverse_of: 'loan_transaction'
  accepts_nested_attributes_for :transitions
end

When I try to do something like "Loan::Transaction.first.transitions" I get the following error: ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column loan_transaction_transitions.transaction_id does not exist) LINE 1: ... AS one FROM "loan_transaction_transitions" WHERE "loan_tran...

But I have tried to specify that in many ways. Nothing worked so far. I'm using docker-compose 3.7 for the postrgreSQL and another container for the web server.

CodePudding user response:

I managed to "fix" it by changing the migration field "loan_transaction" -> "transaction" and the foreign key value in Transition class. Not ideal tough

CodePudding user response:

Why did you created Transition as a sub to Transactions? Wouldn't it be better to have something named Loan::TransactionTransitions

  • Related