Loop in Ruby on Rails html.erb file

ⅰ亾dé卋堺 提交于 2019-12-09 07:38:05

问题


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 %>

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


回答1:


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

Using first

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

Using 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:

@users = User.limit(10)



回答2:


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

@users = User.limit(10)



回答3:


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:

@users.first(10) or @users.last(10)



来源:https://stackoverflow.com/questions/24558916/loop-in-ruby-on-rails-html-erb-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!