【问题标题】:Using variable instead of symbol in update_attribute在 update_attribute 中使用变量而不是符号
【发布时间】:2012-10-28 21:44:36
【问题描述】:

我对这一切都很陌生,所以请对我的知识做最坏的假设。关于

record = tablename.new
result["top"].each do |r|    #result is the answer from a variable length JSON
  if ActiveRecord::Base.connection.column_exists?(:tablename, r["aaa"]["bbb"] )
    record.update_attribute(r["aaa"]["bbb"] , r["ccc"] )
  else
    ActiveRecord::Base.connection.add_column(:tablename, r["aaa"]["bbb"] , :integer )
    #record.update_attribute( r["aaa"]["bbb"] , r["ccc"] )
  end
record.save

我收到此错误,因为我在 update_attribute 中使用了变量而不是符号:

undefined method `stringify_keys' for "contents of r["aaa"]["bbb"]":String (NoMethodError)

但我不能使用符号,因为我实际上并不知道列的名称 - 它都是动态生成的,从这一行可以看出:

ActiveRecord::Base.connection.add_column(:tablename, r["aaa"]["bbb"] , :integer )

简而言之,我如何适应具有 update_attribute 的可变列名?

【问题讨论】:

  • String 上没有 stringify_keys 方法。就此而言,也不是在符号上。
  • 嗯,我不知道堆栈跟踪是什么,但完整的错误是:/home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2 .3/lib/active_record/attribute_assignment.rb:69:in assign_attributes': undefined method stringify_keys' for "contents of r["aaa"]["bbb"]":String (NoMethodError)

标签: ruby activerecord


【解决方案1】:

您可以使用 String#to_sym 将字符串转换为符号

record.update_attribute(r["aaa"]["bbb"].to_sym , r["ccc"] )

【讨论】:

  • 好建议,但这让我遇到了这个错误,时间戳是数据库中先前建立的列:active_model/attribute_methods.rb:407:in method_missing': undefined method contents of r["aaa"][" bbb"],然后出于某种原因,等号 =' #tablename id: nil, timestamp: "2012-10-28 13:01:47"> (NoMethodError)
  • record.update_attribute(:foo, "something") 有效地执行record.foo = "something"; record.save,因此您需要在数据库中使用foo 列来保存它。无论r["aaa"]["bbb"] 返回什么,您的表中有列吗?
  • 是的,add_column 按预期插入列名 r["aaa"]["bbb"] 如果它们不存在。
  • 您应该在创建列后调用tablename.reset_column_information 为您的模型刷新 ActiveRecord 缓存。
【解决方案2】:

很抱歉,但没有足够的评论点数。

edouardbriere 回答了您的问题,但您能解释一下您的用例吗?由于某些数据而编辑架构几乎从来都不是正确的做事方式。

【讨论】:

    猜你喜欢
    • 2014-09-28
    • 2021-01-23
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多