我的模板看起来像:
<h2>Oracle</h2> <% @q_oracle.each do |q| %> <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br> <% end %> <h2>Ruby and Rails</h2> <% @q_ruby.each do |q| %> <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br> <% end %>
所以temlate包括静态标题(h2)和循环遍历数组.我正在寻找避免在我的模板中复制粘贴代码的方式.就像是:
@hash = { 'Oracle' => @q_oracle,'Ruby and Rails' => @q_ruby } @hash.each { |@t,@a| <h2>@t</h2> <% @a.each do |q| %> <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br> <% end %> }
可能吗?
解决方法
是的,你可以做到
Ruby 1.9解决方案
在Ruby 1.8中,这个解决方案可以在标题顺序无关紧要时使用.在Ruby 1.9标题中,它们将以哈希方式插入.
只需将此变量放在您的控制器操作中即可:
@hash = { 'Oracle' => @q_oracle,'Ruby and Rails' => @q_ruby }
并从您的视图访问此变量:
<% @hash.each do |t,a| %> <h2><%= t %></h2> <% a.each do |q| %> <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br> <% end %> <% end %>
具有排序键的Ruby 1.8
<% @hash.keys.sort.each do |t| %> <h2><%= t %></h2> <% @hash[t].each do |q| %> <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br> <% end %> <% end %>
Ruby 1.8与数组
这种方法在任何Ruby版本中都将像Ruby 1.9一样运行 – 标题会按照添加的方式出现.
变量@hash必须初始化为:
@hash = [ ['Oracle',@q_oracle],['Ruby and Rails',@q_ruby] ]
视图必须更新为:
<% @hash.each do |title_with_questions| %> <h2><%= title_with_questions[0] %></h2> <% title_with_questions[1].each do |q| %> <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br> <% end %> <% end %>