在 Ruby on Rails html.erb 文件中循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24558916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop in Ruby on Rails html.erb file
提问by Stark_kids
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:
我是 Ruby on Rails 的新手,我需要了解一些东西。我有一个实例变量 (@users),我需要在 html.erb 文件中循环遍历它有限的次数。我已经用过这个:
<% @users.each do |users| %>
<%= do something %>
<%end %>
But I need to limitate it to, let's say, 10 times. What can I do?
但我需要将其限制为,比如说,10 次。我能做什么?
回答by infused
If @users
has more elements than you want to loop over, you can use first
or slice
:
如果@users
元素多于您想要循环的元素,您可以使用first
或slice
:
Using first
使用 first
<% @users.first(10).each do |users| %>
<%= do something %>
<% end %>
Using slice
使用 slice
<% @users.slice(0, 10).each do |users| %>
<%= do something %>
<% end %>
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 数组中的其余用户,则应该只加载所需数量的用户limit
:
@users = User.limit(10)
回答by Santhosh
You could do
你可以做
<% for i in 0..9 do %>
<%= @users[i].name %>
<% end %>
But if you need only 10 users in the view, then you can limit it in the controller itself
但是如果视图中只需要 10 个用户,那么您可以在控制器本身中对其进行限制
@users = User.limit(10)
回答by Mohamed El Mahallawy
Why don't you limit the users?
为什么不限制用户?
<%= @users.limit(10).each do |user| %>
...
<%end%>
That'd still use ActiveRecord so you get the benefit of AR functions. You can also do a number of things too such as:
那仍然会使用 ActiveRecord,因此您可以获得 AR 功能的好处。您还可以做很多事情,例如:
@users.first(10)
or @users.last(10)
@users.first(10)
或者 @users.last(10)