0

I am trying to render a partial from within a js.erb file which has both a collection AND a local variable passed to it. Everything works fine except I cannot access the local variable in the view. I have tried the following:

<%= escape_javascript(render(partial: 'tasks/task', collection: @task_group.tasks_belonging_to, as: :task, locals: {testvble: "bob"})) %>
<%= escape_javascript(render(partial: 'tasks/task', collection: @task_group.tasks_belonging_to, locals: {testvble: "bob"})) %>
<%= escape_javascript(render(partial: @task_group.tasks_belonging_to, locals: {testvble: "bob"})) %>
<%= escape_javascript(render(@task_group.tasks_belonging_to, testvble: "bob")) %>

Each of the above works until I try to access the local variable in the view. I get the error:

undefined local variable or method `testvble'

Just for completeness, each of the above is inside the following statement in the js.erb file (at the xxxx position):

$("#task-group-<%=@task_group.id%>").append("xxxx").hide().show('slow')

This is the code in the partial causing the issue:

<p>should be bob:<%= testvble %></p>
mahi-man
  • 4,326
  • 2
  • 25
  • 36
  • Are you on Rails 4? The last of the 4 render statements you show should be working. Can you post the snippet of code from the partial where you reference testvble? – J Plato Mar 05 '15 at 04:33
  • Yes, I'm on Rails 4.2. I edited the above with the code from the partial causing the issue – mahi-man Mar 05 '15 at 06:37
  • I think I found the problem. The partial itself calls itself recursively when there are child tasks to display, and the partial was not passing on the variable to the child. So yes the bottom syntax works (the others may work too now, but I'll stick to the most concise one). Thanks! – mahi-man Mar 05 '15 at 07:00
  • I've done that. Glad you found it -- good luck! – J Plato Mar 05 '15 at 13:04

1 Answers1

0

The bottom syntax is actually correct as suggested by J Plato. My issue was that the partial recursively called itself if there were child tasks to display. When rendering the child task(s) the local variable was not being passed on.

mahi-man
  • 4,326
  • 2
  • 25
  • 36