Passing @object into a rails partial render

For Rails 3+, the answer to your actual question is:

<%= render 'profiles/show', :@profile => blah %>

Your partial will now see @profile locally.

I'm not saying this is a good approach. I'm honestly not sure if this is ugly or not. But it works.


Indeed, quoting this blog post you should know:

A partial is a reusable view template, it allow you to modularize the components which make up a particular page into logical, cohesive pieces. When required data is not passed into a partial, it is often difficult to reuse or change later.

The rails guides site explains some simple use cases:

You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content ...

So in your specific case there is a simple and powerful way to do that

<%= render partial: 'show', locals: {profile: @profile} %>

Extra tip:
Probably a partial named show is not a good option, give it a more meaningful name related to the thing you are trying to reuse. This sounds even more error/confusion prone in a RESTful scenario when you actually have a show method, so probably would be a _show.html.erb file and a show.html.erb file.

Hope this helped.


You could always do @profile = profile in the partial.


Why is it so important that you use an instance variable(variables who's names begin with '@', eg: @object) in your partial? It's not a good habit to get into. Using instance variables in partials complicates the control flow, which facilitates bugs and makes reuse of partials more difficult. This blog post explains the problem a little more in depth.

Really you have two options. The first option is the suggested solution.

  1. Change all instance variables to a local variable and pass it to the partial with the locals argument of render.

  2. Set the instance variable before the partial is rendered. Partials have access to all the instance variables that your controller sets.

Again instance variables in partials are bad. You should never set instance variables just because your partials are already written to use them. Rewrite the partial instead.