TypeError:nil不是符号

只是尝试使用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 pe e.save if e.card and e.deck end 

我运行上面的代码。

架构:

 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 

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

 # (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' 

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

编辑:变量’main’设置在显示的上方。

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

对于那些来到这里并且需要添加主键的人,您可以在这样的迁移中执行此操作:

class AddIdToMyTable < ActiveRecord::Migration def change add_column :my_table, :id, :primary_key end end