简体   繁体   中英

In a Rails controller creating a new index in a 'map.do' loop fails, yet it's fine in Ruby

I have a bunch of records from a database using select id, parent_id.... and loop over them using map.do creating a new index on each row.

records = results.map do |row|
    row['childs'] = {}
    comments[row['id']] = row
end

This works fine when called from the command-line but when placed in the Rails context I get the following error:

>ActiveModel::MissingAttributeError in CommentsController#index
can't write unknown attribute `childs'

Any idea what this would work in Ruby at the command line and not Rails? What am I missing about how Rails works?

row is not a hash, but an ActiveModel object instance, so you can't just add/assign new attributes to it like a key to the hash. In your model, you can use attr_accessor to initiate setters(writing) and getters(reading) for childs attribute.

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