Rail 4拒绝将记录保存到数据库 - belongs_to

时间:2014-06-12 16:57:36

标签: ruby-on-rails rails-activerecord rails-console

问题

如果rails控制台有belongs_to关联,则它不会将我的记录保存到数据库中。

2.1.1 :002 > Track.create name: 'asdfasdf'
(0.1ms)  begin transaction
SQL (0.6ms)  INSERT INTO "records" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2014-06-12 15:58:20.868095"], ["updated_at", "2014-06-12 15:58:20.868095"]]
(45.9ms)  commit transaction
=> #<Track id: nil, record_id: 1, name: "asdfasdf", created_at: nil, updated_at: nil>



class Record < ActiveRecord::Base
  has_many :tracks
  accepts_nested_attributes_for :tracks, allow_destroy: true
end

class Track < ActiveRecord::Base
  belongs_to :record
end

class CreateRecords < ActiveRecord::Migration
  def change
    create_table :records do |t|
      t.string :title
      t.timestamps
    end
  end
end

class CreateTracks < ActiveRecord::Migration
  def change
    create_table :tracks do |t|
      t.belongs_to :record
      t.string :name
      t.timestamps
    end
  end
end

如您所见:id字段为nil。 :record_id字段改为递增。 我已经尝试重置主键,问题仍然存在。然而,这不是我的主要原因,因为插入后甚至没有保存记录。

2.1.1 :003 > Track.last
Track Load (0.3ms)  SELECT  "tracks".* FROM "tracks"   ORDER BY "tracks"."id" DESC LIMIT 1
=> nil

这是一个问题,因为它阻止我使用this one等嵌套表单。当我下载并运行that rails app时,它非常有用。它可以很好地工作。

2.1.1 :002 > Answer.create content: 'swwaaagggggs'
(0.2ms)  begin transaction
SQL (0.8ms)  INSERT INTO "answers" ("content", "created_at", "updated_at") VALUES (?, ?, ?)  [["content", "swwaaagggggs"], ["created_at", "2014-06-12 16:46:04.989529"], ["updated_at", "2014-06-12 16:46:04.989529"]]
(58.9ms)  commit transaction
=> #<Answer id: 3, question_id: nil, content: "swwaaagggggs", created_at: "2014-06-12 16:46:04", updated_at: "2014-06-12 16:46:04">

然而,当我完全重新创建它时,我遇到了同样的问题。

奇怪

如果我回滚迁移并删除关联,我会得到这个。

2.1.1 :003 > Track.create name: 'swagger'
(0.2ms)  begin transaction
SQL (0.7ms)  INSERT INTO "records" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2014-06-12 16:06:12.443845"], ["updated_at", "2014-06-12 16:06:12.443845"]]
(0.2ms)  rollback transaction
ActiveModel::MissingAttributeError: can't write unknown attribute `record_id'



class Record < ActiveRecord::Base
end

class Track < ActiveRecord::Base
end

class CreateRecords < ActiveRecord::Migration
  def change
    create_table :records do |t|
      t.string :title
      t.timestamps
    end
  end
end

class CreateTracks < ActiveRecord::Migration
  def change
    create_table :tracks do |t|
      t.string :name
      t.timestamps
    end
  end
end

当列不再存在时,请注意对:record_id的引用

我不知所措。

Google已经用完了网页,似乎没有其他人遇到这个问题导致我认为过去2天我的代码出现了问题。 “这个记录得很好的东西不应该这么难,”我想。如果有人能帮我解决这个问题,我将不胜感激。

如果您需要更多信息,请告诉我这是我第一次感觉需要发布到StackOverflow。

1 个答案:

答案 0 :(得分:3)