Rails 6.0 has_many - belongs_to无法识别外键

Rails 6.0 has_many - belongs_to failing to identify the foreign key

提问人:Bruno Aguiar de Souza 提问时间:8/4/2022 最后编辑:Bruno Aguiar de Souza 更新时间:8/4/2022 访问量:55

问:

我有 2 个模型 Loan::Transaction 和 Loan::Transaction::Transition。它们都在文件夹“models”和“loan”中。第二个也在文件夹“transaction”中。

1 Loan::Transaction 有很多 Loan::Transaction::Transition 1 Loan::Transaction::Transition
属于 1 Loan::Transaction

Loan::Transaction::Transition 的列loan_transaction_id

迁移:

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

过渡类:

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

交易类:

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

当我尝试执行“Loan::Transaction.first.transitions”之类的操作时,出现以下错误: ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column loan_transaction_transitions.transaction_id does not exist) 第 1 行:......作为“loan_transaction_transitions”中的一员,其中“loan_tran......

但我试图以多种方式说明这一点。到目前为止没有任何效果。我正在为postrgreSQL使用docker-compose 3.7,为Web服务器使用另一个容器。

Ruby-on-Rails 命名空间 Ruby-on-rails-6 has-many

评论

0赞 Mike Szyndel 8/4/2022
你真的不应该这样命名类。 是命名空间,其本身是一个类,而不是一个模块。如果这是新代码,我鼓励您将其重命名为 Loan::TransactionTransition'TransitionTransaction
0赞 Bruno Aguiar de Souza 8/4/2022
在任何地方更改类名及其位置后,仍然存在相同的问题
0赞 Mike Szyndel 8/5/2022
异常会告诉您该怎么做。它期望列名是,而你有transaction_idloan_transaction_id

答:

1赞 Bruno Aguiar de Souza 8/4/2022 #1

我设法通过更改迁移字段“loan_transaction”->“transaction”和 Transition 类中的外键值来“修复”它。不理想,坚韧