如何让ActiveModel成为哈希或数组?

hey*_*ike 3 ruby activerecord ruby-on-rails

 class Post< ActiveRecord::Base                                                                                                                                                                                                            
 end   

post_array = Post.first
Run Code Online (Sandbox Code Playgroud)

如果我想在p中添加一些数据.

post_array['test'] = nil
Run Code Online (Sandbox Code Playgroud)

这会产生错误:

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'
Run Code Online (Sandbox Code Playgroud)

我认为原因是:github中的这个提交:当使用不存在的属性的write_attribute时引发错误

如何在post_array中插入一些数据,即post_array['test'] = nil

也许有一些方法可以将这个ActiveModel转换为哈希或数组?

Ver*_*cus 5

你可以这样做:

post = Post.first
hash = post.attributes
hash['test'] = 'test'
Run Code Online (Sandbox Code Playgroud)

但是你可能不想:我想你在这里需要在一个对象上存储一些数据,而模型都是关于将数据存储在自己身上.如果您希望将此数据持久保存到数据存储区,则应编写包含此列的迁移.如果没有,那么你应该在你的模型中使用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.
Run Code Online (Sandbox Code Playgroud)

一般情况下,除非您将模型的数据转换为其他格式(如JSON或plist等),否则将其更改为哈希通常只会让您的生活变得更加困难.