Note that there are some explanatory texts on larger screens.

plurals
  1. POruby on rails looping through a list of key value elements
    primarykey
    data
    text
    <p>I have a list of key value pairs like this. </p> <pre><code> PERSON_SUMMARY = { first_names: %w(Mike Tim Jim kevin Alan Sara John Sammy t'Renée), last_names: %w(Robinson Jackson Fox Terry Ali Brits Tyson Willis-St.\ Paul), offenses: [ { offense_name:'Speeding', penalties: [ { penalty_name: 'Prison', severity: 'Medium' }, { penalty_name: 'Ticket', severity: 'Low' } ] }, { offense_name:'Shoplifting', penalties: [ { penalty_name: 'Prison', severity: 'Medium' }, { penalty_name: 'Fine', severity: 'Low' } ] } ] } </code></pre> <p>I want to store and print only <strong>offense_name</strong>,**penalty_name** and <strong>severity</strong> one by one , but I am not able to get the right syntax.</p> <p>Here is what I have tried so far:</p> <pre><code>PERSON_SUMMARY[:offenses].each do |offense| offense_name = offense[:offense_name] offense[:penalties].each do |penalty| penalty_name = penalty[:penalty_name] severity_val = penalty[:severity] end end </code></pre> <p>EDIT: Eventually I need to insert it into the database table through this function:</p> <pre><code>PersonOffense.where(person_id: person.id).first_or_create( name: offense_name, penalty: penalty_name , severity: severity_val end </code></pre> <p>But I notice an issue, there are multiple penalty names above. Not sure how to insert them.</p> <p>For example, I need to insert offense_name twice in my table so that there are 2 entries in the table.</p> <pre><code>Speeding Prison Medium Speeding Ticket Low </code></pre> <p>EDIT: I like Jesse's answer below. How can I use it to insert it in the same order to my method above (inserting offense_name,penalty_name and severity with the result of the answer given below by Jesse.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload