0

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 ?

1
  • It's little bit difficult to Understand your question, Can you give some details regarding your models. Commented Aug 23, 2011 at 11:00

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Hopefully yes, but the question suggest otherwise I think... :/
0

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

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.