简体   繁体   中英

mapping to value in deep hash

I'm doing an application using mongodb and mongoid and I'm facing a problem where I need to map something in one document to something in another document. My plan is to store something in a document that I can then use to figure out what value for it to fetch from a different collection. But, this is more generally a ruby question about how I can fetch data from deep within a hash.

I have a structure something like this:

Widget
  Sections
    0
      Fields
        0
          value: foobar

If that makes sense. Let's say I want to get the value of the first field in the first section, I would do something like:

@widget.sections[0].fields[0].value

No problem.

Now the question is, how can I do this with all of that as a string? What I want to do is store within the database a mapping value. So I've have a key/value with something like:

mapping: "sections[0].fields[0].value"

Now how can I use that to get the data from @widget? I've tried @widget.send "sections[0].fields[0].value" but that does not work... I can do @widget.send "sections" and get back an array of sections, but I'm not quite sure how to take it further...

So to summarize, I can do this:

@widget.sections[0].fields[0].value

if I have @widget and a string "sections[0].fields[0].value" how can I execute that?

@widget.instance_eval("sections[0].fields[0].value")

应该可以。

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