简体   繁体   中英

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. 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

edit - looks like the problem is because I am using the html under pins and so it doesn't know what is appetizers

edit- solved. looks like i had to change the def index of my pins controller to also include @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...

 <% @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.

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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