【问题标题】:TypeError: nil is not a symbol类型错误:nil 不是符号
【发布时间】:2014-10-26 00:59:12
【问题描述】:

只是尝试使用 ActiveRecord 保存,但我不断收到“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

我运行上面的代码。

架构:

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。

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

请任何帮助。我在这上面花了几个小时。我尝试了 mysql insteal 的 sqlite。我尝试了不同的列数据类型。问题是“数量”这一领域。它不会让我保存。

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

【问题讨论】:

标签: mysql ruby-on-rails ruby activerecord


【解决方案1】:

好的,我终于找到了答案。我制作了连接表,没有 id 字段的“条目”。如果将连接表用作带有额外数据的模型,则需要这样做。

【讨论】:

  • 这是否记录在任何地方?我尝试对我的连接表做同样的事情,但我仍然遇到同样的错误。此外,您可能应该接受自己的答案。
  • 我读过的任何文档中都没有提到这一点,我已经广泛搜索了这个问题,因为过去两天我一直被这个问题所困扰。我有一个连接表,它使用has_and_belongs_to_many 作为我迁移到has_many :through 的关联;连接表仍然没有任何id,因此任何更新记录的尝试都失败了。现在我知道为什么会发生这种情况了,我希望 Google 能在这里为其他人带来与排名第一的结果相同的问题。
  • 另外,如果您不想添加主键,您可以使用update_all 方法 - see here。如果您尝试更新特定记录,可以先执行where 子句,然后执行update_all
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多