简体   繁体   中英

Accessing keys from an hash whose values are arrays in ruby

I have the following hash:

@types = {"source-1"=>["type1", "type2"], "source-2"=>["type3", "type4"]}

I am doing the following in my haml :

%ul
      - @types.values.flatten.each do |type|
        - if @sources.include? type
          %input#types{:name => "types[]", :type => "checkbox", :value=> "#{type}", checked: :true, readonly: "readonly"}/
          %label{:for => "types"} "#{type}"
        - else
          %input#types{:name => "types[]", :type => "checkbox", :value=> "#{type}"}/
          %label{:for => "types"} "#{type}"

Doing this helps me display the different types appropriately with checkboxes. I want to include an extra tag like source_id in the %input#types so that i can associate each type to the source-id . For example

 %input#types{:source_id = source-1 , :name => "types[]", :type => "checkbox", :value=> type2 , checked: :true, readonly: "readonly"}/

here source_id is source-1 is type2 belongs to source-1 .

is there a simpler way of doing this than having to do @types.map{|k,v|k if v.include?type}-[nil] inside the tag in haml

I would also be able to access the source_id in the controller for the selected types

Try this:

- @types.each do |source,types|
  - types.each do |type|
    - if @sources.include? type
      %input#types{ :source_id => source, :name => "types[]", :type => "checkbox", :value=> "#{type}", checked: :true, readonly: "readonly"}/
      %label{:for => "types"} "#{type}"
    - else
      %input#types{ :source_id => source, :name => "types[]", :type => "checkbox", :value=> "#{type}"}/
      %label{:for => "types"} "#{type}"

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