Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – 在模板中循环大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的模板看起来像:
<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 %>

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – 在模板中循环全部内容,希望文章能够帮你解决ruby-on-rails – 在模板中循环所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。