class Post< ActiveRecord::Base
end
post_array = Post.first
If I want to add some data into p.
post_array['test'] = nil
this will make errors:
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'
I think the reason is : this commit in github: Raise error when using write_attribute with a non-existent attribute
How can I insert some data into post_array , ie, post_array['test'] = nil?
Maybe there is some methods can convert this ActiveModel into hash or array?
You can do this like so:
post = Post.first
hash = post.attributes
hash['test'] = 'test'
However you probably don't want to: I imagine you're struggling here with needing to store some data on an object, and models are all about storing data on themselves. If you want this data persisted to your datastore, you should write a migration that includes this column. If not, then you should use attr_accessor in your model:
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.
Generally unless you're converting the model's data to a different format (like JSON or plist or something), changing it into a hash will usually just make your life more difficult.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With