简体   繁体   English

在Ruby on Rails中循环.each

[英]Looping .each in Ruby on Rails

For my food menu database I have a structure like this: 对于我的食物菜单数据库,我有一个像这样的结构:

The master table contains the type of food such as appetizers, soup, beef, etc... 主表包含食物的类型,例如开胃菜,汤,牛肉等。

Then I have tables titled appetizers, soup, beef, etc... that will hold the food items. 然后我有一张名为开胃菜,汤,牛肉等的桌子,上面放着食物。

I plan to iterate the master table and for each food type, I will iterate the respective table to create my page. 我计划迭代主表,对于每种食物类型,我将迭代各自的表以创建我的页面。

I wrote the code as: 我写的代码为:

  <% @pins.each do |pin| %>
    <% @(pin.foodtype).each do |type| %>
        test
    <% end %>
  <% end %>

The first line should iterate the master table for appetizers and using that, I should be able to call the appetizers table using pin.foodtype and iterate through the appetizers table. 第一行应该迭代开胃菜的主表,并使用它,我应该能够使用pin.foodtype调用开胃菜表并遍历开胃菜表。 However I get an error for the second line. 但是,第二行出现错误。

How can I solve this issue and is there a better database structure to do this? 如何解决此问题,是否有更好的数据库结构来做到这一点?

Thanks 谢谢

screenshot: puu.sh/iGwQB/0fab4c3547.png 屏幕截图:puu.sh/iGwQB/0fab4c3547.png

edit - looks like the problem is because I am using the html under pins and so it doesn't know what is appetizers 编辑-看起来问题是因为我在别针下使用html,所以它不知道什么是开胃菜

edit- solved. 编辑解决。 looks like i had to change the def index of my pins controller to also include @appetizers = Appetizer.all 看起来我不得不更改pin控制器的def索引,使其也包含@appetizers = Appetizer.all

edit- it seems that even though I can do @appetizers I cant do it with pin.foodtype because it is a string... 编辑-似乎即使我可以@appetizers我也不能用pin.foodtype做到这一点,因为它是一个字符串...

 <% @pins.each do |pin| %>
    <% pin.foodtype.each do |type| %>
        test
    <% end %>
  <% end %>

This should do. 这应该做。 '@' is used for declaring an instance variable, you don't need to use it in loops. “ @”用于声明实例变量,您无需在循环中使用它。 The local variable 'pin' is already declared, and if it has the associate foodtype with it, it will work. 已经声明了局部变量“ pin”,如果它具有关联的食物类型,它将起作用。

And yes, probably you meant 'foodtypes' instead of 'foodtype'? 是的,可能您的意思是“食物类型”而不是“食物类型”?

Give this a try- 尝试一下

<% @pins.each do |pin| %>
  <% pin.foodtype.classify.constantize.all.each do |type| %>
    test
  <% end %>
<% end %>

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

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