Richlewis
Richlewis

Reputation: 15374

Passing variable through partial and Ajax call

I am looking to find out how I can pass a variable through an Ajax call with Rails, using a .js.erb file.

At the moment I am declaring this in my view

<% document = @documents.select { |d| d.skill_id == s.id } %> 

<div class="doc_upload">
  <%= render partial: 'shared/documents/document_form', locals: { document: document } %>
</div>

shared/documents/document_form

<% if document %>
  <% document.each do |doc| %>
    <%= doc %>
  <% end %>
  <%= render template: '/documents/new' %>
<% else %>
  <%= render template: '/documents/new' %>
<% end %>

So when I create a new document I am handling it with an Ajax call

create.js.erb

$('.doc_upload').html("<%= j render(partial: 'shared/documents/document_form', locals: { document: document }) %>")

However I get an undefined local variable or methoddocument'`

Is there a reason I can't access document any more?

Upvotes: 0

Views: 552

Answers (2)

Hardik Hardiya
Hardik Hardiya

Reputation: 847

in create.js.erb change

$('.doc_upload').html("<%= j render(partial: 'shared/documents/document_form', locals: { document: document }) %>")

with

$('.doc_upload').html("<%= j render(partial: 'shared/documents/document_form', locals: { document: @document }) %>") 

& it will work.

Upvotes: 0

Finks
Finks

Reputation: 1681

It's because document variable is not defined. You need to either pass in @document found in the controller or initialize document in the js.erb file.

edit: check your js.erb, in the local hash, you can clearly see that you're passing document variable but it's not defined anywhere.

Upvotes: 1

Related Questions