how to create an array in a helper and then loop through in a view
I have a poll, and I've created a helper to return a JSON object of all the results which works like so:
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
Then in the view I want to call it and loop through the options and output the title, etc...
<% poll_results_json(@poll)['options'].each do |poll_option| %>
<%= poll_option['id'] %>
<%= poll_option['title'] %>
<%= poll_option['vote_percentage'] %>
<%= poll_option['vote_count'] %>
<% end %>
The view is erroring. What's the right way to loop through the resulting JSON object?
Thanks
Your problem is, you want to iterate through JSON data, not a Ruby array. This is because to_json
just returns a Ruby string with valid JSON inside. So instead of converting your whole Poll
objects into JSON, you should just return the values as 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 %>
I don't know why your are pushing Hash into an Array(@poll_results).Instead try something like
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
The value returned from the method will be a string.first you need to parse json to process it.
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 %>
精彩评论