Rails _id有时不会添加到查询中

时间:2014-07-02 11:57:40

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个班级:

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'

当我尝试创建路线时,问题出现了。设置origindestinationtransfer(可能为零)后,我有:

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附加到origindestination(正如我所料),但由于某些原因我不明白,它 hasn 't 将其附加到key_transfer_country,因此SELECT失败。

有人可以帮我找出原因吗?

1 个答案:

答案 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

这是因为字段名称的长度不能出于某种原因假设外键的名称。试试吧。

抱歉我的英文