0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

thanks for the help...how can i access the local hash?
you misunderstood me. If you check your create.js.erb, you've written something like this -> <%= j render(partial: 'shared/documents/document_form', locals: { document: document }) as you can see, you have a parameter named locals which has the hash of { document: document }. Just change it to local: { document: @document } and if your code is ok, it will be all good.
Another tip, you can rephrase that into something like this: <%= j render 'shared/documents/document_form, document: @document` %>
ah i see, but i thought it would be able to access it from the document declaration in my view, but im now thinking that because im only rendering the partial with the ajax call, anything outside of that partial is no longer accessible? so how would i pass through the document variable?
the js.erb is a separate view. It doesn't know anything about the current view you've used the AJAX. The only thing it knows is the controller action, which is, create. So redefine @document in your create action in your controller and you'll be good.
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.