TypeError:nil不是符号

Kev*_*abe 12 ruby mysql activerecord ruby-on-rails

只是尝试使用ActiveRecord保存,我不断得到"TypeError:nil不是符号"

if card_data[:card] and card_data[:deck]
  e = self.find_or_create_by(card_id: card_data[:card].id, deck_id: card_data[:deck].id, main: main)
  e.card = card_data[:card]
  e.deck = card_data[:deck]
  e.quantity = card_data[:quantity].to_i
  e.main = main
  p e
  e.save if e.card and e.deck
end
Run Code Online (Sandbox Code Playgroud)

我运行上面的代码.

架构:

create_table "entries", id: false, force: true do |t|
  t.integer  "card_id"
  t.integer  "deck_id"
  t.integer  "quantity",   default: 0, null: false
  t.integer  "main",       default: 0, null: false
  t.datetime "created_at"
  t.datetime "updated_at"
end
Run Code Online (Sandbox Code Playgroud)

当我使用pry时,在find_or_create_by之后它甚至不会立即让我e.save.

#<Entry card_id: 1, deck_id: 1, quantity: 4, main: 1, created_at: "2014-10-26 00:45:12", updated_at: "2014-10-26 00:45:12">
(0.2ms)  BEGIN
(0.2ms)  ROLLBACK
TypeError: nil is not a symbol
from /home/kevin/.rvm/gems/ruby-2.1.2/gems/activemodel-4.1.6/lib/active_model/dirty.rb:162:in `attribute_was'
Run Code Online (Sandbox Code Playgroud)

请帮忙.我花了好几个小时.我试过sqlite的mysql insteal.我尝试了不同的列数据类型.问题是字段"数量".它不会让我保存.

编辑:变量'main'设置在显示的上方.

Kev*_*abe 29

好的,我终于找到了答案.我创建了连接表,没有id字段的'entries'.如果将连接表用作具有额外数​​据的模型,则需要这样做.

  • 在我读过的任何文档中都没有提到这一点,而且由于过去两天我一直受到这个问题的困扰,因此我搜索了这篇文章.我有一个连接表,使用`has_and_belongs_to_many`作为关联,我迁移到`has_many:through`; 连接表仍然没有任何`id`,因此任何更新记录的尝试都失败了.现在我知道为什么会发生这种情况,我希望Google在这里带来与#1结果相同的问题. (2认同)
  • 此外,如果您不想添加主键,可以使用`update_all`方法 - [请参阅此处](http://stackoverflow.com/questions/13263188/how-do-you-update-a-join -table记录与 - 无主密钥功能于导轨).如果您正在尝试更新特定记录,则可以先执行`where`子句,然后执行`update_all`. (2认同)