在Ruby on Rails html.erb文件中循环 [英] Loop in Ruby on Rails html.erb file

查看:89
本文介绍了在Ruby on Rails html.erb文件中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人 我是Ruby on Rails的新手,我需要了解一些东西.我有一个实例变量(@users),我需要在html.erb文件中循环有限次数. 我已经用过了:

everybody I'm brand new with Ruby on Rails and I need to understand something. I have an instance variable (@users) and I need to loop over it inside an html.erb file a limitated number of times. I already used this:

<% @users.each do |users| %>
   <%= do something %>
<%end %>

但是我需要将其限制为10次.我该怎么办?

But I need to limitate it to, let's say, 10 times. What can I do?

推荐答案

如果@users的元素多于要循环的元素,则可以使用firstslice:

If @users has more elements than you want to loop over, you can use first or slice:

使用first

<% @users.first(10).each do |users| %>
  <%= do something %>
<% end %>

使用slice

<% @users.slice(0, 10).each do |users| %>
  <%= do something %>
<% end %>

但是,如果实际上不需要@users数组中的其余用户,则应该仅使用limit加载所需的数量:

However, if you don't actually need the rest of the users in the @users array, you should only load as many as you need by using limit:

@users = User.limit(10)

这篇关于在Ruby on Rails html.erb文件中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆