Returning a hash from controller to a view using a helper
Warning I'm brand new to rails! While reading through a tutorial it has asked me to place a hash of string keys with decimal values into the products action method (My assumption they are talking about the "def products" in the controller.
In reguards to using the products method in the controller did I place my hash correctly? In reguards to the placing the information from the hash into a table do I even need the helper method or is there a better way? My helper needs help and doesn't format the data correctly using .html_safe I
This is what I have so far in my controler:
def products
#hard coded as products in controller
@stuff = {"a"=>200.00, "b"=>150.00, "c"=>100.00, "d"=>9.00, "e"=>15.00, "f"=>20.00 }
end
This is what I have in my product.html.erb file
<%= form_tag(products_path) do %>
<table id="aboutus_table">
<%= products_tabler() %>
</table>
<% end %>
and then the helper...it needs help
def products_tabler
snowholder = @开发者_运维技巧snow_stuff.each {|key,value|puts "<tr><td>#{key}</td><td>#{value}</td><tr>"}
return snowholder
end
puts
is probably a mistake, you don't really want to print to standard out in a web service. See if this works?
def products_tabler
snowholder = ""
@snow_stuff.each {|key,value| snowholder += "<tr><td>#{key}</td><td>#{value}</td><tr>"}
return snowholder
end
I realize this is a tutorial, but using a helper that emits hardcoded html is not an improvement over having the html in the view itself.
In this case, it's really simple to do it in the view:
<table id="aboutus_table">
<% @snow_stuff.each do |key, value| %>
<tr>
<td><%= key %></td><td><%= value %></td>
</tr>
<% end %>
</table>
If you really wanted to separate the creation of the rows, a collection partial would be better. Then Rails does the iteration for you. Use this technique when you've got real data (i.e. ActiveRecords instead of hashes).
<table id="aboutus_table">
<%= render :partial => "row", :collection => @stuff %>
</table>
Then the _row partial would contain:
<tr>
<td><%= row.name %></td><td><%= row.value %></td>
</tr>
精彩评论