views:

797

answers:

1

I am trying to access an instance variable from a js.erb file.

#controller
def get_person
  @person = Person.find(1)

  respond_to do |format|
   format.js{}
  end
end

#get_person.js.erb
alert('<%= @person.last_name %>')

When I browse to [controller_name_here]/get_person.js ... I get a nil object error on @person. (I know Person.find(1) returns an object)

Note: I am actually having trouble rendering a partial in my js.erb file and am trying to identify the cause.

+1  A: 

The following works for me:

In /app/controllers/foo_controller.rb:
class FooController < ApplicationController
  def get_person
    @person = Person.find(1)
    respond_to do |format|
      format.js
    end
  end
end
In /app/views/foo/get_person.js.erb:
<%= render :partial => '/foo/some_partial', :locals => { :person => @person } %>
In /app/views/foo/_some_partial.js.erb:
person = {
  last_name: '<%= person.last_name -%>'
}
James A. Rosen
This is strange, instance variables are intended to be visible in all partials so the locals construct should not be necessary (in this particular case). There is something else amiss here.
Cody Caughlan
that's really strange. I get "The error occurred while evaluating nil.last_name"
Lee
Lee: you're sure you're using "<%= person.last_name -%>" and not "<%= @person.last_name -%>" in the partial?
James A. Rosen
Lee: if you _are_ using person.last_name in the partial and you're still seeing "The error occurred while evaluating nil.last_name" (instead of "undefined local variable or method 'person'"), then the Person.find(1) is your problem!
James A. Rosen