首页 > 解决方案 > 更新 gem 后 Rails 未定义列错误

问题描述

我正在升级我的投资组合网站,在那里我上传了一个新的视频文件,当我在本地服务器上检查它时,页面看起来不错,然后由于安全问题,我决定更新 sprockets 和 bootstrap。

我跑了一个bundle updatebundle install我升级到了 sprockets 3.2.7 和 Bootstrap 4.1.2,而在它之前是 4.0alpha。

我已经消除了 Bootstrap gem 的可能性。

在此之后,我的博客页面和只有我的博客页面出现以下错误消息:

PG::UndefinedColumn: 错误: 列 blogs.topic_id 不存在

来自_blog_sidebar.html.erb

<div class="sidebar-module">
    <h4>Topics</h4>
    <% @side_bar_topics.each do |topic| %>
      <p><%= link_to topic.title, topic_path(topic) %></p>
    <% end %>
  </div>

它指向每个循环说我缺少模型topic_id上的字段Blog

更新 gems 是如何发生的?有没有人发生过这种情况?如果是这样,您是如何解决的?

这是我的schema.rb文件,您可以在其中看到topic_id

ActiveRecord::Schema.define(version: 20170930175841) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "topics", force: :cascade do |t|
    t.string "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "blogs", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.integer "status", default: 0
    t.bigint "topic_id"
    t.index ["slug"], name: "index_blogs_on_slug", unique: true
    t.index ["topic_id"], name: "index_blogs_on_topic_id"
  end

我遵循了has_manybelongs_to约定: https ://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

blog.rb

class Blog < ApplicationRecord
  enum status: {draft: 0, published: 1}
  extend FriendlyId

  friendly_id :title, use: :slugged

  validates_presence_of :title, :body, :topic_id

  belongs_to :topic

  has_many :comments, dependent: :destroy

  def self.special_blogs
    all
  end

  def self.featured_blogs
    limit(2)
  end

  def self.recent
    order("created_at DESC")
  end
end

topic.rb

class Topic < ApplicationRecord
    validates_presence_of :title

    has_many :blogs

    def self.with_blogs
        includes(:blogs).where.not(blogs: {id: nil})
    end
end

标签: ruby-on-rails

解决方案


我通过运行rake db:drop, rake db:create,来修复它rake db:migrate


推荐阅读