Rails: accessing an instance variable in a js.erb file?

Up vote 5 down vote favorite share g+ share fb share tw.

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('') 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. Javascript ruby-on-rails ruby ajax link|improve this question edited Jun 3 '09 at 19:56 asked Jun 3 '09 at 19:02Lee5841419 65% accept rate.

If so, you should know that partials don't have access to the class variables of their caller. You need to pass in anything that you want it to have access to. – workmad3 Jun 3 '09 at 19:15 Since I am creating the partial in my js.

Erb file, shouldn't my js. Erb file have access to class variables? – Lee Jun 3 '09 at 19:20 No.

You have to pass them in as locals: 'partials/foo', :locals => {:whatwhat => @somedata}) %> – jonnii Jun 3 '09 at 19:28 1 As an aside, you don't need the empty braces in the format. Js line. – John Topley Jun 3 '09 at 19:34 ok, so I tried rendering the partial in the js.

Erb files like so: $("#members"). Append(" 'partialname', :locals => {:person => @person} ))%>"); but in partial I still an getting a nil object error on person....this is what led me to try and break down the problem. – Lee Jun 3 '09 at 19:40.

The following works for me: In /app/controllers/foo_controller. Rb: class FooController '/foo/some_partial', :locals => { :person => @person } %> In /app/views/foo/_some_partial.js. Erb: person = { last_name: '' }.

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 Jun 3 '09 at 21:10 that's really strange.

I get "The error occurred while evaluating nil. Last_name" – Lee Jun 3 '09 at 21:12 Lee: you're sure you're using "" and not "" in the partial? – James A.

Rosen Jun 4 '09 at 13:07 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 Jun 4 '09 at 13:09.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions