Rails 5创建含外键的Flight模型实例时出现SQLite3错误
解决ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: main.destination_airports错误
这个问题我之前也碰到过,大概率是关联设置或者数据库迁移的问题,咱们一步步排查:
检查Flight模型的关联代码
你需要确保Flight模型里的关联是单数形式的,因为belongs_to后面要跟模型的单数名称,而不是复数。正确的写法应该是:class Flight < ApplicationRecord belongs_to :origin_airport, class_name: "Airport" belongs_to :destination_airport, class_name: "Airport" end要是你写成了
belongs_to :destination_airports(复数),Rails就会去查找destination_airports表,这肯定是不存在的,因为你的机场表应该是airports。确认数据库迁移文件的正确性
你的Flight表迁移文件里必须包含两个外键字段:origin_airport_id和destination_airport_id,用来关联Airport表。迁移文件应该类似这样:class CreateFlights < ActiveRecord::Migration[6.1] def change create_table :flights do |t| t.references :origin_airport, null: false, foreign_key: true t.references :destination_airport, null: false, foreign_key: { to_table: :airports } # 其他字段比如起飞时间之类的 t.timestamps end end end注意这里
destination_airport的外键要指定to_table: :airports,因为Rails默认会去找destination_airports表,这时候手动指定关联到airports表就解决问题了。确保迁移已正确执行
有时候可能迁移文件改了但没重新执行,先回滚之前的迁移(如果有的话):rails db:rollback然后重新执行迁移:
rails db:migrate这样能保证数据库表结构是最新的。
检查Airport模型的反向关联
为了让关联双向生效,Airport模型里应该这样写:class Airport < ApplicationRecord has_many :origin_flights, class_name: "Flight", foreign_key: "origin_airport_id" has_many :destination_flights, class_name: "Flight", foreign_key: "destination_airport_id" end这里指定
class_name和foreign_key是因为Rails没法自动推断出这两个关联对应的航班外键,必须手动告诉它。
按照上面的步骤排查一遍,应该就能解决这个找不到表的问题了。
内容的提问来源于stack exchange,提问作者Kyle Lemon
相关产品推荐
相关产品推荐

