从散列中访问键,其值为ruby中的数组

时间:2014-09-30 16:45:08

标签: ruby-on-rails ruby ruby-on-rails-4 haml

我有以下哈希:

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

我在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}"

这样做有助于我通过复选框适当地显示不同的类型。我想在%input#types中包含一个额外的标签,如source_id,以便我可以将每种类型与source-id相关联。例如

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

此处source_id source-1 type2属于source-1

是否有更简单的方法来执行此操作,而不必在haml中的标记内执行@types.map{|k,v|k if v.include?type}-[nil]

我还可以访问控制器中所选类型的source_id

1 个答案:

答案 0 :(得分:0)

试试这个:

- @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}"