简体   繁体   中英

Add new attribute to existing hash

I am retrieving results using Mongoid, but I want to add a new attribute to each of the records returned in an instance variable using the key. How would I go about doing this?

In PHP I would do this by looping through the array and inserting it based on the key of the object. I am unable to figure out how this can be done in Ruby when I receive the message: Model ABC can't be converted into an Integer.

Update: I ended up adding a method in the model to achieve what I was trying to do.

I'll try to point you in the right direction.

If you have an array of records and what to loop through it, use Array#each: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-each

You can write attributes easily: http://rdoc.info/github/mongoid/mongoid/Mongoid/Attributes#write_attribute-instance_method

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM