【问题标题】:Rails update_attributes trying to insert id columnRails update_attributes 尝试插入 id 列
【发布时间】:2013-01-09 19:33:03
【问题描述】:

我有一个模型:

class MyModel < ActiveRecord::Base
  has_many :other_things
  accepts_nested_attributes_for :other_things
  attr_accessible :other_things_attributes
end

class OtherThing < ActiveRecord::Base
  belongs_to :my_model
  attr_accessible :foo
end

当尝试在 MyModel 实例上更新属性时,Rails/ActiveRecord 尝试将 null 插入到 id 列中:

my_instance = MyModel.first
my_instance.update_attributes({
  "other_things_attributes"=> {
    "1357758179583" => {"foo"=>"bar", "_destroy"=>"false"},
    "1357758184445" => {"foo"=>"thing", "_destroy"=>"false"}
  }
})

失败了,有:

  SQL (0.5ms)  INSERT INTO "other_things" ("created_at", "my_model_id", "id", "updated_at", "foo") VALUES ($1, $2, $3, $4, $5)  [["created_at", Wed, 09 Jan 2013 14:30:33 EST -05:00], ["my_model_id", 8761], ["id", nil], ["updated_at", Wed, 09 Jan 2013 14:30:33 EST -05:00], ["foo", "bar"]]
   (0.1ms)  ROLLBACK 
ActiveRecord::StatementInvalid: PGError: ERROR:  null value in column "id" violates not-null constraint
: INSERT INTO "other_things" ("created_at", "my_model_id", "id", "updated_at", "foo") VALUES ($1, $2, $3, $4, $5)

显示 other_things 的架构:

  create_table "other_things", :force => true do |t|
    t.string   "foo"
    t.integer  "my_model_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

这没有显示主键约束(或缺少主键约束),这是根本问题。

【问题讨论】:

  • 你能在这里张贴db/scheme.rb 中显示other_things 表方案的部分吗?
  • 已更新以显示请求的信息;还回答了最近发现的缺少主键约束的潜在问题。

标签: sql ruby-on-rails insert primary-key rails-activerecord


【解决方案1】:

这是由于不知何故丢失了 other_things 表上的主键规范。我之所以确定这一点,是因为我必须将它在一个但不能在另一个中工作的实例(暂存和生产)分开;在比较了代码和 Rails 相关问题之后,我决定比较 DB 模式,这表明我缺少主键约束。显然,Rails 使用主键来识别正确的列;直观上是显而易见的,但在我看来,如果你还不知道的话。感谢 cmets!

ALTER TABLE ONLY other_things ADD CONSTRAINT other_things_pkey PRIMARY KEY (id);

【讨论】:

    【解决方案2】:

    有类似的问题,我通过使用 update_columns 而不是 update_attributes 解决了。希望它会帮助某人。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2010-12-23
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多