Hi if I have a loop in my controller that for example goes through a product list and for each product found goes through another loop that finds the price for that product. Having in mind that products and prices are in different models because one product can have many prices, how do i display the results in the view ?
3 Answers
In the ProductsController you fetch products including the prices
def index
@products = Product.all
end
In the view you can loop over the products
<ul>
<% @products.each do |p| %>
<li><%=p.name %> / <%=p.price.value %></li>
<%end%>
</ul>
1 Comment
You should build associations between your models, instead of manually collecting all data in different loops. Associations are used to link different models (database tables) to each other. In your case the product and the price models.
For more information on associations, take a look at the Guide to Active Record Associations.
Comments
It is really hard to say with so little information but It depends on how is your
model associations and In which view you want to display such information.
If it is on show page then you do not required any extra loop in your controller.
If you want to use for indexing then please try to use for_each instead of .all and collect the required info into object and use that object within the view.