【问题标题】:rails object.association.count postgres errorrails object.association.count postgres错误
【发布时间】:2012-08-12 06:59:03
【问题描述】:

我刚刚将我的数据库从 mysql 更改为 postgres,但出现以下错误:

ActionView::Template::Error (PG::Error: ERROR:  operator does not exist: character varying = integer
LINE 1: ...ELECT COUNT(*) FROM "agents"  WHERE "agents"."client_id" = 1

什么时候做

client.agents.count

我有一个数据结构如下:客户有几个代理,如果agents.count < X,只能添加更多代理,所以我使用client.agents.count之类的东西来检索这个值并进行比较,但我得到了那个错误。我需要使用手动 sql 来完成这项工作吗?还是我错过了什么愚蠢的东西?

感谢您的cmets

型号信息

class Agent < User

  belongs_to :client
  attr_accessible :client_id

  validates :client_id, presence: true


end

class Client < User
  attr_accessible :appId, :expire_date, :legacy, :url, :plan_id, :chat_window_color, :chat_head_color, :chat_box_container_color, :chat_box_color, :tab_message, :greeting, :please_wait_message, :send_message_button, :comments_label, :offline_message

  belongs_to :plan
  has_many :agents, :dependent => :destroy

  has_secure_password

  after_initialize :init

  #omited validations

  private
  #BEGIN PRIVATE METHODS
end

都继承自用户

class User < ActiveRecord::Base
    self.abstract_class = true

  attr_accessible :email, :name, :password, :password_confirmation

  attr_accessor :updating_password

  has_secure_password

  before_save { self.email.downcase! }

  #the controller must set updating_password to FALSE to avoid validation
  def should_update_password?
    updating_password || new_record?    
  end

end

【问题讨论】:

  • 请出示您在app/models/agent.rbapp/models/client.rb中的代码
  • 然后是执行上述操作的控制器代码。
  • 在看到导致问题的实际代码之前,我们无法解决问题。
  • 更新了我的问题以显示代理/客户端/用户模型,谢谢
  • 问题不在控制器中,而是在客户端配置文件的视图中,它是@client.agents.count@michael-durrant

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

所以我发现了问题,列 client_id 是 varchar,mysql 允许这样做,但 postgres 抱怨不同的数据类型。通过做这样的事情得到了一个很好的工作:

def up
  rename_column :agents, :client_id, :client_id_old
  add_column :agents, :client_id, :integer
  Agent.reset_column_information
  Agent.find_each { |c| c.update_attribute(:client_id, c.client_id_old) } 
  remove_column :agents, :client_id_old
end

从此链接How do I change column type in Heroku?


为了避免在 postgres 中直接使用 change_column 更改数据类型时出现问题。希望这对其他人有帮助

【讨论】:

    猜你喜欢
    • 2014-10-24
    • 2014-04-14
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2018-03-02
    • 2013-01-10
    • 1970-01-01
    相关资源
    最近更新 更多