class Post< ActiveRecord::Base
end
post_array = Post.first
如果我想在p中添加一些数据。
post_array['test'] = nil
这会产生错误:
ActiveModel::MissingAttributeError: can't write unknown attribute \`ff'
from ......rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/attribute_methods/write.rb:34:in `write_attribute'
我认为原因是:this commit in github: Raise error when using write_attribute with a non-existent attribute
如何在post_array中插入一些数据,即post_array['test'] = nil
?
也许有一些方法可以将这个ActiveModel转换为哈希或数组?
答案 0 :(得分:5)
你可以这样做:
post = Post.first
hash = post.attributes
hash['test'] = 'test'
但是你可能不想:我想你在这里需要在一个对象上存储一些数据,而模型都是关于将数据存储在自己身上。如果您希望将此数据持久保存到数据存储区,则应编写包含此列的迁移。如果没有,那么你应该在你的模型中使用attr_accessor:
class Post < ActiveRecord::Base
attr_accessor :test
end
post.test = 'test' # Now assigns 'test' to post correctly, and you can read it out the same way.
一般情况下,除非您将模型的数据转换为其他格式(如JSON或plist等),否则将其更改为哈希通常只会让您的生活变得更加困难。