ruby-on-rails – 在模板中循环

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在模板中循环前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的模板看起来像:
  1. <h2>Oracle</h2>
  2.  
  3. <% @q_oracle.each do |q| %>
  4. <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br>
  5.  
  6. <% end %>
  7.  
  8.  
  9. <h2>Ruby and Rails</h2>
  10.  
  11. <% @q_ruby.each do |q| %>
  12. <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br>
  13.  
  14. <% end %>

所以temlate包括静态标题(h2)和循环遍历数组.我正在寻找避免在我的模板中复制粘贴代码的方式.就像是:

  1. @hash = { 'Oracle' => @q_oracle,'Ruby and Rails' => @q_ruby }
  2.  
  3. @hash.each { |@t,@a|
  4.  
  5. <h2>@t</h2>
  6.  
  7. <% @a.each do |q| %>
  8. <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br>
  9.  
  10. <% end %>
  11. }

可能吗?

解决方法

是的,你可以做到

Ruby 1.9解决方

在Ruby 1.8中,这个解决方案可以在标题顺序无关紧要时使用.在Ruby 1.9标题中,它们将以哈希方式插入.

只需将此变量放在您的控制器操作中即可:

  1. @hash = { 'Oracle' => @q_oracle,'Ruby and Rails' => @q_ruby }

并从您的视图访问此变量:

  1. <% @hash.each do |t,a| %>
  2. <h2><%= t %></h2>
  3. <% a.each do |q| %>
  4. <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br>
  5. <% end %>
  6. <% end %>

具有排序键的Ruby 1.8

这种方法排序键,使其按字母顺序显示.

  1. <% @hash.keys.sort.each do |t| %>
  2. <h2><%= t %></h2>
  3. <% @hash[t].each do |q| %>
  4. <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br>
  5. <% end %>
  6. <% end %>

Ruby 1.8与数组

这种方法在任何Ruby版本中都将像Ruby 1.9一样运行 – 标题会按照添加的方式出现.

变量@hash必须初始化为:

  1. @hash = [ ['Oracle',@q_oracle],['Ruby and Rails',@q_ruby] ]

视图必须更新为:

  1. <% @hash.each do |title_with_questions| %>
  2. <h2><%= title_with_questions[0] %></h2>
  3. <% title_with_questions[1].each do |q| %>
  4. <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %> </br>
  5. <% end %>
  6. <% end %>

猜你在找的Ruby相关文章