Rails: Render a View (not a partial) From Within a View Rails: Render a View (not a partial) From Within a View ruby-on-rails ruby-on-rails

Rails: Render a View (not a partial) From Within a View


Rendering a non-partial view inside another view isn't exactly the Rails Way™. Your current solution is probably better, and not an uncommon approach. Rename it _body, or something else appropriate, if you feel weird about the the partial name being the same as the action.

However if your view can be shared, as it seems like it could in this case, you could just make it a layout.

This is facilitated by the fact that, somewhat against the principle of least surprise, Rails will render an html template for a js action if no js template exists. This means that you could remove both the js template, and the partial, and just create a layout entitled, for example, fadein.js.erb:

# yourviews/show.html.erb<div>Content!</div># layouts/fadein.js.erb$("#main").fadeIn("<%= escape_javascript(yield) %>");# YourController.rbdef show  # ...  respond_to do |wants|    wants.html    wants.js { render :layout => "fadein" }  endend


Like others have mentioned, rendering another non-partial view in another view is "Not the rails way", if however you still insist on doing it, one method is:

<%= render :file => '<replace with relative/absolute path>' %>


This is not a good practice as you can see by the comments. Rails have the concepts of view, partial and layout. That said, the view is the only one you should keep using only once. So my suggestions are:

  1. If you feel that more than one extra view could be rendered inside your current view, you are most likely looking for a layout
  2. If you feel that one of your views should be rendered in many pages, you are looking for a partial
  3. If this view should render only one extra view inside it, and that view should only be rendered inside the current view, you can pick any of the above or none of it - that's it, go with a single file