0

我有两个不相关的表,我需要同时循环并调用每个表的不同属性。所以目前我有(为简单起见使用通用名称):

<% @combined = Tableone.all + Tabletwo.all %>
<% @combined.each do |c| %>
<% if c.is_a?(Tableone) %> 
     do some code....
<% elsif c.is_a?(Tabletwo) %>
     do other code...
<% end %>
<% end %>

因此,目前尚未到达 elsif 块,仅显示 Tableone 结果。我怎样才能解决这个问题并遍历两个表?

编辑:这是完整的代码。

<% @subcategory = Subcategory.all %>
<% @product = Product.all %>
<% @ps = Product.all + Subcategory.all %>

<% @ps.each do |ps| %>

    <% if (ps).is_a?(Product) %>
    <% if (ps).display_on_home_page and !(ps).is_highlight_product and !(ps == '..') %>
        <% if ps.price_from %>
            <div class="column_entry">
           <div class="product_special">
            <span class="a">From Only</span>
            <span class="b"><%= number_to_currency(ps.price,:unit=>'€') %></span></div>
                <%= link_to image_tag(ps.product_image.url(:normal_page_size)), products_content_url(ps.id), :controller=>'products' %>
            </div>
         <% else %>
            <div class="column_entry">
            <div class="product_special">
            <span class="a">Only</span>
            <span class="b"><%= number_to_currency(ps.price,:unit=>'€') %></span>
            </div>
            <%= link_to image_tag(ps.product_image.url(:normal_page_size)), products_content_url(ps.id), :controller=>'products' %>
            </div>
            <% end %>
    <% elsif (ps).is_a?(Subcategory) %>
        <%= "Reached elsif" %>
        <% if (ps).display_on_home_page and !(ps).is_highlight_product and !(ps == '..') %>
        <div class="column_entry">
            <%= link_to image_tag(ps.image_attachment.url(:normal_page_size)), subcategories_content_url(ps.id), :controller=>'subcategories' %>
        </div>                          
    <% end %>                                                           
    <% end %>

<% end %>
<% end %>
4

1 回答 1

0

所以,终于想通了。问题是 @ps 是在 HTML 中定义的。在控制器中定义 @ps 如下:

@ps = Products.where(:display_on_home_page=>true) + Subcategory.where(:display_on_home_page=>true)

意味着循环将看到产品和子类别。我不完全确定为什么这不是按照惯例,变量声明应该在控制器中。

于 2013-11-12T16:02:14.157 回答