【问题标题】:How return all elements array in Rails?如何在 Rails 中返回所有元素数组?
【发布时间】:2013-07-30 12:57:27
【问题描述】:

我有一个控制器:

def grafico_gantt 
    @mapa = Hash.new
    @mapa[:tasks] = []
    @projeto.atividades.each do |a|
        @mapa[:tasks] << {
           id:a.id,
           descricao:a.descricao,
           status:a.status,
           data_inicial:a.data_inicial.to_datetime.to_i*1000,
           tempo_gasto:a.tempo_gasto.to_i,
           data_final:a.data_final.to_datetime.to_i*1000
        }
    end
end

还有一个 .js.erb

<script>
    $(function() {
        "use strict";
        $(".gantt").gantt({
            source: [{
                name: '<%= raw @mapa[:tasks][0][:descricao] %>',
                desc: '<%= raw @mapa[:tasks][0][:status] %>'+"% concluído",
                values: [{
                    from: "/Date(<%= raw @mapa[:tasks][0][:data_inicial] %>)/",
                    to: "/Date(<%= raw @mapa[:tasks][0][:data_final] %>)/",
                    label:"<%= raw @mapa[:tasks][0][:descricao] %>", 
                    customClass: "ganttRed"
                }]
            }],
        scale: "days",
        minScale: "days",
        maxScale:"months",
        navigate: "scroll",
        waitText: "Aguarde...",
    });
</script>

我在数组中有 3 个值,但是,怎么看,我只取 1,@mapa[:tasks][0][:descricao] 一个怎么能取所有值?因为@mapa[:tasks][:descricao] 不起作用:/

谢谢!

【问题讨论】:

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


    【解决方案1】:

    首先,我将编写控制器更像这样(未经测试的)代码:

    def grafico_gantt 
      @mapa = {}
      @mapa[:tasks] = @projeto.atividades.map { |a|
        {
          id: a.id,
          descricao: a.descricao,
          status: a.status,
          data_inicial: a.data_inicial.to_datetime.to_i * 1000,
          tempo_gasto: a.tempo_gasto.to_i,
          data_final: a.data_final.to_datetime.to_i * 1000
        }
      }
    end
    

    要访问返回数组的所有 descricao 元素,请使用 mapcollect 将数组转换为您想要的部分:

    @mapa[:tasks].collect { |e| e[:descricao] }
    

    mapcollect 是同义词。尽管它们有别名,但有时使用collect 在语法上更有意义,有时map 更有意义。

    在上面代码的重写中,为什么要创建哈希散列有点令人困惑。散列的单个元素散列有点......令人困惑......不雅,但也许你没有向我们展示一切。

    如果没有其他内容添加到哈希中,我建议将其简化为:

    def grafico_gantt 
      @mapa = @projeto.atividades.map { |a|
        {
          id: a.id,
          descricao: a.descricao,
          status: a.status,
          data_inicial: a.data_inicial.to_datetime.to_i * 1000,
          tempo_gasto: a.tempo_gasto.to_i,
          data_final: a.data_final.to_datetime.to_i * 1000
        }
      }
    end
    

    这将返回一个哈希数组并通过消除查找[:tasks] 元素的需要来简化您对其的访问:

    @mapa.collect { |e| e[:descricao] }
    

    【讨论】:

    • 感谢您的帮助!!!奇怪的是不和我一起工作......我认为必须继续使用我的旧代码:l 但是,非常感谢-
    【解决方案2】:

    这是怎么回事:

    @mapa[:tasks].each{|e| puts e[:descricao] }
    

    @mapa[:tasks].map{|e| e[:descricao] }
    

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      相关资源
      最近更新 更多