Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: nil is not a symbol

Simply trying to save with ActiveRecord and it I keep getting "TypeError: nil is not a symbol"

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

I run the above code.

Schema:

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

When I use pry, it won't let me e.save even immediately after I find_or_create_by.

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

Please any help. I've spent hours on this. I tried mysql insteal of sqlite. I tried different column datatypes. The issue is the field 'quantity'. It won't let me save.

Edit: variable 'main' is set above what is shown.

like image 860
Kevin McCabe Avatar asked Oct 26 '14 00:10

Kevin McCabe


2 Answers

Ok I finally found the answer. I made the join table, 'entries' without an id field. This is require if using the join table as a model with extra data on it.

like image 104
Kevin McCabe Avatar answered Nov 13 '22 15:11

Kevin McCabe


For those of you coming here and needing to add the primary key, you can do it in a migration like this:

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

like image 38
phil Avatar answered Nov 13 '22 15:11

phil