Rails 应用试图更新不存在的列

Rails app trying to update a nonexistent column

这是在 Ruby 1.9.3 和 Rails 3.2.19 上。我对 Rails 不是很有经验。今天我开始只在我们的实时服务器上遇到这个问题,在开发服务器上一切正常。

每当我尝试给 publication model new tags 时,我都会收到此错误:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column "taggings_count" does not exist
LINE 1: UPDATE "tags" SET "taggings_count" = OALESCE("taggings_count", 0) + 1 WHERE "tags"."id" = 47:  
  app/controllers/publications_controller.rb:162:in 'block in update'
  app/controllers/publications_controller.rb:161:in 'update'

控制器的第162行是:

def update
    @publication = Publication.find(params[:id])
    if params[:clear_virtual_performances]
      @publication.virtual_performances.each {|vp| vp.destroy}
    end

    if media_id = params["selected_media"]
      pub_ids = @publication.publication_media_ids
      PublicationMedia.update(@publication.publication_media_ids, [{:selected => false}] * pub_ids.length)
      PublicationMedia.update(media_id, :selected => true)
    end

    respond_to do |format|
      if @publication.update_attributes(params[:publication])  // <-------------------
        expire_fragments
        flash[:notice] = 'Publication was successfully updated.'
        format.html { redirect_to(:action => 'show') }
        format.xml  { head :ok }
      else
        load_extra_vars_for_edit_form
                        Category.in_slug(params[:default_category])
        format.html { render :action => "edit" }
        format.xml  { render :xml => @publication.errors,
                             :status => :unprocessable_entity }
      end
    end
  end

但是,标签中不存在 "taggings_count" 列,我不知道为什么它首先要更新它。事实上,table 上有以下列:idnamepositioncategory_id,以及tag_group_id。这是标签模型:

class Tag < ActiveRecord::Base
  has_many   :taggings
  belongs_to :category
  belongs_to :tag_group

  attr_accessible :name, :position, :category_id, :tag_group_id
end

如果我需要提供更多信息,请告诉我;尽快解决这个问题至关重要。我所需要的只是不发生错误,即使这意味着创建一个虚拟列或其他东西。

我猜你在标记中定义了一个 counter_cache 属性,类似于 belongs_to :publication, counter_cache: true。这导致计数器自动递增。

您可以删除 counter_cache: true 或进行迁移以添加该列。