Question

I have a resource called Exercises in my application. I currently have a partial called _exercise.html.erb that I use to render them. I have an outlying case where I'd like to render them in a much different way. Can I make another partial for exercises that has this other format and still be able to use <%= render @exercises %>?

If not what is the best approach? Should I out a variable in the controller that tells the partial which layout to use, this would have both layout in one file and one if to decide. Or is there some better way?

Was it helpful?

Solution

If you'd like to use business logic to determine when to show what partial for your @exercises collection you should use the to_partial_path method in the Exercise model to define that. See #4 in this post: http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/

Or, if this is more of a view-related decision (i.e. one view will always use the regular _exercises.html.erb and another view would always use e.g. _alternate_exercises.html.erb) then you can specify as such:

<%= render partial: 'alternate_exercises', collection: @exercises, as: :exercise %>

This will render the _alternate_exercises.html.erb partial once for each item in @execrises passing the item in to the partial via a local_assign called exercise.

OTHER TIPS

In this case, I suppose you have two options:

1) Put the conditional code inside of _exercises.html.erb

eg.

<% if @exercise.meets_some_condition %>
 you see this stuff
<% else %>
 you see other stuff
<% end %>

This way, you can still make use of <%= render @exercises %>

2) Otherwise, your other option is to have separate partials and render them outside.

eg.

<% @exercises.each do |exercise| %>
  <% if exercise.meets_some_condition %>    
     <%= render "exercises/some_condition_exercise" %>
  <% else %>
     <%= render "exercises/exercise" %>
  <% end  %>
<% end %>

This is the best approach for rendering partial. You can wrap that partial with if else statement in your code. Here is my example

rendering with form called _victim.html.erb

 <%= render :partial => "victim", :locals => {:f => f }%>

rendering without form

<%= render :partial => "victim"%>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top