代码之家  ›  专栏  ›  技术社区  ›  Dex

Rails:在单个页面上呈现Multiple index.html.erb

  •  2
  • Dex  · 技术社区  · 14 年前

    class AnimalsController < ApplicationController
      def index
        @dogs = Dog.all
        @cats = Cat.all
      end
    end
    

    然后在我的视图/animals/index.html.erb中

    <ul class="tabs">
      <li>Dogs</li>
      <li>Cats</li>
    </ul>
    <div id="#dogs">
      <%= render @dogs %>
    </div>
    <div id="#cats">
      <%= render @cats %>
    </div>
    

    重构成部分是实现这一点的唯一方法吗?

    我希望立即静态加载它们,而不必在单击选项卡时执行Ajax.load()。

    2 回复  |  直到 14 年前
        1
  •  3
  •   Shripad Krishna    14 年前

    你的答案就在问题本身。为什么不使用javascript隐藏这两个部分,并在单击它们各自的选项卡时调用它们呢?你根本不需要ajax:)

    既然您没有提到您使用的javascript库,我将给出一个使用jquery的通用解决方案:

    此外,您不需要在各自部门的ID中添加#。更改为:

    <ul class="tabs">
      <li id="dogs">Dogs</li>
      <li id="cats">Cats</li>
    </ul>
    <div id="dogs" class="subTabs">
      <%= render @dogs %><hr />
    </div>
    <div id="cats" class="subTabs">
      <%= render @cats %><hr />
    </div>
    
    
    $(document).ready(function() {
        $('.subTabs').hide(); //Hide the subTabs as soon as the DOM is loaded.
    
        $('li').live('click', function(e) {
            $('.subTabs').hide(); //Calling this again so as to remove an already loaded
                                    tab, if any. You can refactor this part to make it
                                    even simpler.
            $('body').find('.subTabs').attr('id',$(this).attr('id')).show();
                 //This finds the ".subTabs" whose id is the same as the "li" id that
                   was clicked and shows it. Ofcourse, even this can be made even more
                   compact had i known your entire DOM structure.     
        });
    });
    

    编辑:

    希望这有帮助。:)

        2
  •  1
  •   John Bachir    14 年前

    当你说“索引页”时,你真的想使用与另一个控制器的索引相同的代码吗?如果是这样的话,那么部分是最好的策略。