ActiveModel::MissingAttributeError(无法在生产环境中写入未知属性 `order_id`)

ActiveModel::MissingAttributeError (can't write unknown attribute `order_id`) in production

在开发环境中一切正常,但在生产环境中(当部署到 Heroku 时)它抛出 MissingAttributeError。

class Order < ApplicationRecord
  has_many :cart_items, dependent: :destroy
end

class CartItem < ApplicationRecord
  belongs_to :order, optional: true, foreign_key: "order_id"
end

create_table "cart_items", force: :cascade do |t|
  t.integer  "item_id"
  t.integer  "cart_id"
  t.integer  "user_id"
  t.integer  "order_id"
end

当您在本地主机上迁移时,将构建架构以反映您的本地数据库状态,并且它可能与生产不同步。也许您在迁移中更改了某些内容,但 heroku 仍在使用旧版本。 Heroku 运行 是否进行迁移取决于文件名中的时间戳,而不是迁移的内容。

基本上,如果您有已部署的应用程序,请不要更改旧的迁移。如果您不介意销毁生产数据库中的所有数据,运行 heroku pg:reset DATABASE 然后 rake db:migrate again。如果您无法删除数据,仍有一些方法可以解决问题 - 请参阅 Rails rake db:migrate has no effect