Search code examples
ruby-on-rails-3controllerscopepartial

Rails 3 DRY partials?


I have a Rails 3 application with a view that is irritating me. The view is essentially four tabs. Each tab shows a filtered list of records like this:

Tab One

<% @faults.each do |fault| %>
    <%= fault.name %>
<% end %>

Tab Two

<% @faults_pending.each do |fault| %>
    <%= fault.name %>
<% end %>

Tab Three

<% @faults_closed.each do |fault| %>
    <%= fault.name %>
<% end %>

Obviously there is a lot more code that I have missed out. To tidy the view up significantly I considered making a partial for each tab, however, each of those partials would be identical except for the <% @faults.each do |fault| %> line.

Is there a way of having one partial and somehow when rendering the partial set the scope (or method, I can never remember what it's called).


Solution

  • I think you're looking for render's :locals option.

    Tab one

    <%= render :partial => "faults", :locals => { :faults => @faults } %>
    

    Tab two

    <%= render :partial => "faults", :locals => { :faults => @faults_pending } %>
    

    Tab three

    <%= render :partial => "faults", :locals => { :faults => @faults_closed } %>
    

    Partial

    <% faults.each do |fault| %>
      <%= fault.name %>
    <% end %>