【发布时间】: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