我有一个班级:
class Route < ActiveRecord::Base
belongs_to :origin, class_name: 'Airport'
belongs_to :destination, class_name: 'Airport'
belongs_to :key_transfer_country, class_name: 'Country'
end
带有<{p>}的schema.rb
中的相应条目
create_table "routes", force: true do |t|
t.integer "origin_id"
t.integer "destination_id"
t.integer "key_transfer_country_id"
t.datetime "created_at"
t.datetime "updated_at"
end
我的Airport
模型包括:
has_many :from_routes, class_name: 'Route', foreign_key: 'destination_id'
has_many :to_routes, class_name: 'Route', foreign_key: 'origin_id'
我的Country
模型包括:
has_many :transfers, class_name: 'Route', foreign_key: 'key_transfer_country_id'
当我尝试创建路线时,问题出现了。设置origin
,destination
和transfer
(可能为零)后,我有:
route = Route.find_or_create_by(
origin: origin,
destination: destination,
key_transfer_country: transfer
)
但是我收到了SQL错误
no such column: routes.key_transfer_country: SELECT "routes".* FROM "routes" WHERE "routes"."origin_id" = 6658 AND "routes"."destination_id" = 8025 AND "routes"."key_transfer_country" IS NULL LIMIT 1 (ActiveRecord::StatementInvalid)
所以出于某种原因,Rails已将_id
附加到origin
和destination
(正如我所料),但由于某些原因我不明白,它 hasn 't 将其附加到key_transfer_country
,因此SELECT
失败。
有人可以帮我找出原因吗?
答案 0 :(得分:0)
尝试将 foreign_key 添加到您的关系中:key_transfer_country,就像这样
class Route < ActiveRecord::Base
belongs_to :origin, class_name: 'Airport'
belongs_to :destination, class_name: 'Airport'
belongs_to :key_transfer_country, class_name: 'Country', foreign_key: 'key_transfer_country_id'
end
这是因为字段名称的长度不能出于某种原因假设外键的名称。试试吧。
抱歉我的英文