Rails: access to instance variable in js.erb file

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 go to [name_name_name_and _] / get_person.js ... I get a nil object error on @person. (I know that Person.find (1) returns an object)

Note. I'm actually having a partial problem in the js.erb file and trying to determine the cause.

+6
javascript ruby ajax ruby-on-rails
source share
2 answers

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 -%>' } 
+5
source share

The js.erb file no longer has partial fragments. I just discovered this today.

https://github.com/rails/rails/issues/1370

0
source share

All Articles