Loop in Ruby on Rails html.erb file

后端 未结 3 557
梦毁少年i
梦毁少年i 2021-02-05 01:43

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 limitat

相关标签:
3条回答
  • 2021-02-05 02:19

    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)

    0 讨论(0)
  • 2021-02-05 02:36

    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 by using limit:

    @users = User.limit(10)
    
    0 讨论(0)
  • 2021-02-05 02:37

    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)
    
    0 讨论(0)
提交回复
热议问题