【问题标题】:insert to database error on heroku but worked locally, ActiveRecord::StatementInvalid在heroku上插入数据库错误但在本地工作,ActiveRecord::StatementInvalid
【发布时间】:2025-12-04 23:45:01
【问题描述】:

我有 2 个模型:

class User < ActiveRecord::Base
  has_many :micro_posts, :dependent => :destroy
  ..
  def add_post(post)
    self.micro_posts << post
  end

class MicroPost < ActiveRecord::Base
  belongs_to :user
  ...

以及迁移:

class CreateMicroPosts < <ActiveRecord::Migration
  def change
    create_table :micro_posts do |t| 
    ...

当我在 heroku 服务器上调用 add_post 时,出现错误:

2012-02-06T02:59:58+00:00 app[web.1]: ActiveRecord::StatementInvalid (ArgumentError: wrong number of arguments (1 for 0): INSERT INTO "micro_posts" ("created_at", "description", "pub_date", "tag", "title", "updated_at", "url", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"):
2012-02-06T02:59:58+00:00 app[web.1]:   app/models/user.rb:25:in `add_post'

但有线的东西是,它在我的电脑上工作。我的操作系统信息:

ubuntu 10.04
ruby 1.9.3p0
rails 3.1.3
postgresql 8.4.10

谢谢。

【问题讨论】:

  • 乍一看,我看不出您的代码有什么问题。但是我确实注意到您正在运行 PostgreSQL 8.4,因为 Heroku 在 9.0.4(甚至 9.1)上运行。尝试升级您的 Postgres 并查看是否可以在本地重现该错误。这将为您提供更详细的日志记录。
  • 谢谢。我会升级它并尝试。
  • 没有。我将 postgresql 升级到 9.1.2(从源代码构建),它在本地工作。

标签: ruby-on-rails activerecord heroku


【解决方案1】:

我解决了这个问题,但还是不知道为什么。

在 heroku 控制台(heroku 运行控制台)中尝试后,我发现错误不是由我的 add_post 方法引起的。其实是我的 MicroPost.new 造成的:

post = MicroPost.new(..., :pub_date => rss_item.pubDate)

正如这里的代码所示,MicroPost 有一个名为 pub_date 的 datetime 列,该字段来自 RSS 项目 pubDate,此代码将导致以下错误显示(在 heroku 上):

irb(main):020:0> post=MicroPost.new(:description=>"none", :url=>'url',:title=>"title",:pub_date=>item.pubDate,:tag=>"tag")
ArgumentError: wrong number of arguments (1 for 0)
from /usr/local/lib/ruby/1.9.1/time.rb:454:in `rfc2822'
from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.1.3/lib/active_support/time_with_zone.rb:168:in `to_s'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.3/lib/active_record/base.rb:1785:in `attribute_for_inspect'

经过一番谷歌搜索,我找到了解决方案:http://www.spacebabies.nl/2008/06/16/rails-2-and-rss-parsing-gives-weird-errors/

虽然它是 Rails2,但它仍然对我有用。 只需将 item.pubDate 更改为 item.pubDate.to_s

再一次,谁能解释一下这里发生了什么?

ps,item.pubDate 没有错,在控制台我可以打印出来,即:

item.pubDate.class => Time

【讨论】: