开发者

Ruby on Rails Controller Loop

H开发者_Go百科i 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 ?


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>


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜