【问题标题】:how to create an array in a helper and then loop through in a view如何在帮助程序中创建一个数组,然后在视图中循环
【发布时间】:2011-07-23 19:29:53
【问题描述】:

我有一个投票,我创建了一个帮助器来返回一个包含所有结果的 JSON 对象,其工作方式如下:

module PollVotesHelper
  def poll_results_json(poll)

    @poll_results = Array.new

    @poll_results << {
      :total_votes => poll.poll_votes.length,
      :options => poll.poll_options.collect { |poll_option|
        {
          :id => poll_option.id,
          :title => poll_option.title,
          :vote_percentage => '33%',          
          :vote_count => poll_option.poll_votes.length
        }
      }
    }
    @poll_results.to_json
  end

end

然后在视图中我想调用它并遍历选项并输出标题等...

<% poll_results_json(@poll)['options'].each do |poll_option| %>
 <%= poll_option['id'] %>
 <%= poll_option['title'] %>
 <%= poll_option['vote_percentage'] %>
 <%= poll_option['vote_count'] %>
<% end %>

视图出错。遍历生成的 JSON 对象的正确方法是什么?

谢谢

【问题讨论】:

  • 错误 2011-07-23 12:37:39 -0700 错误 (SampleJob#perform): 无法将字符串转换为整数 - (ActionView::Template::Error) ..... html.erb:81:in `[]'
  • 您不想使用散列而不是数组,因为您要存储键/值对吗?
  • 为什么这里需要 JSON?
  • JSON 发送回浏览器。我以多种方式需要这种类型的对象
  • 有没有更好的方法来构建它,既可以作为哈希值,也可以让我通过 json 输出?

标签: ruby-on-rails ruby arrays json ruby-on-rails-3


【解决方案1】:

您的问题是,您想要遍历 JSON 数据,而不是 Ruby 数组。这是因为 to_json 只返回一个 Ruby string ,其中包含有效的 JSON。因此,与其将整个 Poll 对象转换为 JSON,不如将值返回为 JSON:

<% @poll.poll_options.each do |poll_option| %>
  <%= poll_option.id.to_json %>
  <%= poll_option.title.to_json %>
  <%= '33%'.to_json %>
  <%= poll_option.poll_votes.length.to_json %>
<% end %>

【讨论】:

  • 什么?不确定您是说不使用助手吗?我需要帮手来计算输出
  • 我还需要这个 JSON 格式的输出用于其他方法,所以通过在整个应用程序中使用一个 JSON 输出来保持 DRY 可以让事情变得干净
  • 您正在将数据从 Ruby 转换为 JSON,但是要在您的视图中使用这些数据并通过 Ruby 访问它,它必须是 Ruby。您的助手只是在里面返回一个 String (带有 JSON)。您不能直接在 Ruby 中访问 JSON 数据。
  • 因此,您是否尝试过仅使用&lt;%= poll_results_json(@poll) %&gt;,而不是使用我的第一个解决方案(我认为这是最好的:P)。这将起作用,因为您只是在视图中打印一个字符串。
【解决方案2】:

我不知道你为什么将 Hash 推入一个数组(@poll_results)。而是尝试类似

module PollVotesHelper
 def poll_results_json(poll)

  @poll_results = {
    :total_votes => poll.poll_votes.length,
    :options => poll.poll_options.collect { |poll_option|
    {
      :id => poll_option.id,
      :title => poll_option.title,
      :vote_percentage => '33%',          
      :vote_count => poll_option.poll_votes.length
    }
  }
}
  @poll_results.to_json
 end
end

该方法返回的值将是一个字符串。首先你需要解析 json 来处理它。

in your view try like 
<% JSON.parse(poll_results_json(@poll))['options'].each do |poll_option| %>
  <%= poll_option['id'] %>
  <%= poll_option['title'] %>
  <%= poll_option['vote_percentage'] %>
  <%= poll_option['vote_count'] %>
<% end %>

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多