Tutorial :Rails: Rendering Multiple index.html.erb on a Single Page


I am using tabs and want to load multiple index pages into tabs. For instance:

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

Then in my views/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>  

Is refactoring out into a partial the only way to achieve this?

I'd like to have them loaded statically at once and not have to resort to doing an Ajax.load() when the tab is clicked.


You have your answer in the question itself. Why don't you just use javascript to hide the two partials and call them when their respective tab is clicked? You don't need ajax for this at all :)

Since you did not mention the javascript library that you use, I will give a generic solution using jquery:

Also you need not add a # to your respective div's ids. Change it to this:

<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.           });  });  

Edit: You also have to make sure that you style it using CSS to make it look more like tabs if you haven't already. :)

Hope this helps. :)


You typically only want to use a partial if you are using the same or almost the same code in more than one place.

When you say "index page", do you really want to use the same code that is used in an index of another controller? If so, then a partial is the best strategy.

Don't use JavaScript to solve a layout / code organization problem.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »