0

As the title says, I am trying to load a form partial with an AJAX request; one of the fields in my form requires a variable in the controller so it can create the select dropdown menu. If I render the partial directly in the view, it accesses the variable fine but when I separate the partial and try to load it via an AJAX request, it doesn't know how to find the variable.

I have tried following the answer found here (giving it to the partial as a local variable) but it still does not work.

@headers is the variable that is not being loaded.

partial:

= simple_form_for(Constraint.new, html: {:multipart => true, autocomplete: "off", :class=> "form-horizontal" }, remote: true, :authenticity_token => true) do |f|
  div.profile-details
    br
    = f.select :header, @headers.each{|header|} , input_html:{:class => "user-update"}, label: "Header", :prompt   => "Select a Header"
    br
    = f.button :submit, "Save Constraint"

.js file that loads partial:

$(".newConditionContainer").append('<%= escape_javascript(render 'projects/rulesConstraintsInput')%>');

UPDATE:

I ended up defining the variable in the controller method that calls the js request. I had earlier assumed that the variable was accessible but it was only being defined in a method outside of the partial.

1 Answer 1

0

Partials need to begin with an underscore so name it something like _partial_name.html.erb then you can reference a partial using render like this and pass any local variables you like

<%= render partial: "partial_name", locals: {headers: @headers} %>

Headers will be available as a local varaible inside the partial now. Just change @headers to headers

Cheers

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

5 Comments

This is the answer I tried and it still doesn't seem to work. My partial is in a separate file if that helps explain it. It just tries looking for the header variable and saying "NoMethodError - undefined method `each' for nil:NilClass".
How is your .js file getting access to the @headers variable if its stored in your controller?
That's essentially my question. What would be the best way to access that variable?
Couple ways I can think of to do it. A hidden input element which you set the value to your headers var and use JS to retrieve it. Or you could use a templating engine like Handlebars.js, you'll be able to generate a section of reusable html and you can just feed it variables from the controller when you render the view.
Thanks for your help--I ended up just defining said variable in the controller method that calls the js request.

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.