提问人:Bruno Aguiar de Souza 提问时间:8/4/2022 最后编辑:Bruno Aguiar de Souza 更新时间:8/4/2022 访问量:55
Rails 6.0 has_many - belongs_to无法识别外键
Rails 6.0 has_many - belongs_to failing to identify the foreign key
问:
我有 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服务器使用另一个容器。
答:
1赞
Bruno Aguiar de Souza
8/4/2022
#1
我设法通过更改迁移字段“loan_transaction”->“transaction”和 Transition 类中的外键值来“修复”它。不理想,坚韧
评论
Transition
Transaction
transaction_id
loan_transaction_id