【问题标题】:Print array in a helper method在辅助方法中打印数组
【发布时间】:2013-02-07 22:22:28
【问题描述】:

我是 Ruby-on-rails 的新手。我有一个非常简单的问题: 这个在我的视图文件中有效:

- @posts.each do |child|
    = child.name
end

但是,我无法创建一个将数组作为参数并使用 'each' 对其进行迭代的辅助方法。

在我的视图文件中:

=f1(@posts)

在我的帮助文件中:

def f1(abc)
    abc.each do |child|
            puts child.name
    end
end

请帮我解决这个愚蠢的问题。 提前非常感谢

【问题讨论】:

    标签: ruby-on-rails arrays printing


    【解决方案1】:

    这样的东西有用吗?

    def f1(abc)
      output = ''
      abc.each do |child|
        output << "<br/> #{child.name}"
      end
      output
    end
    

    【讨论】:

      【解决方案2】:

      在一个正在运行的 Rails 应用程序中,puts 输出到日志文件中。

      我建议尝试这种方法:

      在帖子视图目录中创建一个'_post'部分,然后使用post作为对象(即:post.name)放置您想要渲染的内容,然后在视图中使用render @posts。这将自动渲染集合中每个对象的部分。

      有关详细信息,请参阅Ruby on Rails Layouts and Rendering Guide 中的第 3.4.5 节

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-27
        • 2016-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多