Understanding Find Requests & Loops Correctly

Good afternoon,

Everyone here has been incredibly helpful in their past support of my
issues, so I’m hoping that I can ask just a few more as I move along in
learning RoR.

I’m generating two grids in a particular view. The first grid displays
the top five selling products (as defined by the field, position) and
then the last grid displaying the remaining products.

The existing find query is as follows:

@product_grid = Product.find(:all, :order => 'position', :conditions

=> {:store_id => current_store.id})

After retrieving all of the information for the relevant products, the
array is passed over to a view that displays it as follows:

<% @product_grid.in_groups_of(5, false) do |row_products| %>

<% for product in row_products %>
<%= product.name%>

<% end %>
<% end %>

How would one go about limiting this loop to only display the first 5
products that were retrieved based on position? Additionally, how would
one use the same grid format to display every product that has a
position greater than 5?

Neil H. wrote:

The existing find query is as follows:
<% for product in row_products %>
<%= product.name%>

<% end %>
<% end %>

How would one go about limiting this loop to only display the first 5
products that were retrieved based on position? Additionally, how would
one use the same grid format to display every product that has a
position greater than 5?

How about:

first_five = @product_grid[0…4]
everything_else = @product_grid[5…@product_grid.length]


Cheers,

  • Jacob

Would that approach toss an error if the total array size was less than
5 when declaring everything_else?

How about:

first_five = @product_grid[0…4]
everything_else = @product_grid[5…@product_grid.length]


Cheers,

  • Jacob

Neil H. wrote:

Would that approach toss an error if the total array size was less than
5 when declaring everything_else?

No, in that case the variable will simply be nil.


Cheers,

  • Jacob A.