简体   繁体   English

Ruby on Rails控制器循环

[英]Ruby on Rails Controller Loop

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 ? 考虑到产品和价格处于不同模型中,因为一种产品可以具有多个价格,我如何在视图中显示结果?

In the ProductsController you fetch products including the prices 在ProductsController中,您可以获取包括价格在内的产品

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 . 有关关联的更多信息,请参阅《 Active Record关联指南》

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. 如果要用于索引编制,请尝试使用for_each而不是.all并将所需的信息收集到对象中并在视图中使用该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM