Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a ActiveModel to became a hash or array?

 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?

like image 858
hey mike Avatar asked Dec 11 '25 22:12

hey mike


1 Answers

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.

like image 63
Veraticus Avatar answered Dec 14 '25 14:12

Veraticus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!